MongoDB :仅更新集合中的那些 'Id' 存在于列表中的对象
MongoDB : Update only those objects in a collection whose 'Id' exists in a list
我有一个 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 Whosebug
{
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();
}
}
}
我有一个 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 Whosebug
{
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();
}
}
}