我有一个需要更新的 MongoDb 集合。 该集合的 JSON 对象由几个元素组成,“Id”就是其中之一。 现在,我只需要更新此集合中“Id”与临时列表“TempList”中的对象相匹配的那些对象。
我尝试做这样的事情,(见下文并注意“filter”参数),但它抛出了一个错误,
await MyAccounts.UpdateManyAsync(w => TempList.Any(y => y.Id == w.Id),
Builder.Update
.Set(w => w.Elem1, blah1)
.Set(w => w.Elem2, blah2)
.AddToSet("Elem3", blah3));
感谢任何帮助!
最佳答案
您需要将 tempList
设置为 ID 列表,以便以下内容正常工作,而不是对象列表。
var filter = Builders<MyAccount>.Filter
.Where(a => tempList.Contains(a.Id));
var update = Builders<MyAccount>.Update
.Set(a => a.Elem1, "blah1")
.Set(a => a.Elem2, "blah2")
.AddToSet("Elem3", "blah3");
collection.UpdateMany(filter, update);
这是一个测试程序:
using MongoDB.Entities;
using MongoDB.Entities.Core;
using System.Linq;
namespace StackOverflow
{
public class Account : Entity
{
public string Elem1 { get; set; }
public string Elem2 { get; set; }
}
public class Program
{
private static void Main(string[] args)
{
new DB("test", "localhost");
(new[]
{
new Account{
Elem1 = "first-elem1",
Elem2 = "first-elem2"
},
new Account{
Elem1 = "second-elem1",
Elem2 = "second-elem2"
},
new Account{
Elem1 = "third-elem1",
Elem2 = "third-elem2"
}
}).Save();
var tempList = DB.Queryable<Account>()
.Select(a => a.ID)
.Take(2)
.ToList();
DB.Update<Account>()
.Match(a => tempList.Contains(a.ID))
.Modify(a => a.Elem1, "blah1")
.Modify(a => a.Elem2, "blah2")
.Modify(a => a.AddToSet("Elem3", "blah3"))
.Execute();
}
}
}
关于node.js - MongoDB : Update only those objects in a collection whose 'Id' exists in a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59041275/