node.js - MongoDB : Update only those objects in a collection whose 'Id' exists in a list

标签 node.js mongodb linq mongoose c#-4.0

我有一个需要更新的 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/

相关文章:

json - 如何在 nunjucks 中使用 JSON.parse

node.js - 无法加载c++ bson扩展,使用纯JS版本

c# - 如何在 C# 的通用列表中查找重复的顺序条目?

c# - LINQ to Entities 以不同方式使用日期时间

c# - 如何在 lambda 中执行 sql 连接?

node.js - Mongoose - 使用 findoneandupdate 和 $push 添加或更新子文档(当 upsert 为 true 时)

node.js - 部署到heroku Angular 4

javascript - Socket.io 教程不打印到控制台的连接

mongodb - mongodump - 文件名、目录名或卷标语法不正确

java - 将查询 mongo 转换为 spring Mongooperations