简体   繁体   English

在 MongoDB 中更新文档时如何插入字段?

[英]How do I interpolate a field when updating documents in MongoDB?

I have a collection that looks like this:我有一个看起来像这样的集合:

{ 
    "_id" : ObjectId("5e5777b74db43342073051e0"), 
    "a" : "b"
}
{ 
    "a" : "c", 
    "_id" : ObjectId("5e5777f24db43342073051e4")
}

And I want to copy the value of each document's a into a new array field so I end up with this:我想将每个文档的a值复制到一个新的数组字段中,所以我最终得到了这个:

{ 
    "_id" : ObjectId("5e5777b74db43342073051e0"), 
    "a" : "b",
    "d": ["b"]
}
{ 
    "_id" : ObjectId("5e5777f24db43342073051e4"),
    "a" : "c", 
    "d": ["c"]
}

I tried this command at the shell:我在 shell 中尝试了这个命令:

db.getCollection("C").updateMany({}, {
    $set: {
        "d.0": "$a"
    }
});

But that gave me:但这给了我:

{ 
    "_id" : ObjectId("5e5777b74db43342073051e0"), 
    "a" : "b", 
    "d" : {
        "0" : "$a"
    }
}
{ 
    "_id" : ObjectId("5e5777f24db43342073051e4"), 
    "a" : "c", 
    "d" : {
        "0" : "$a"
    }
}

$$a gave me the same result. $$a给了我同样的结果。 How do I write this operation?这个操作怎么写?

In Mongo 4.2 the <update> document can also be an aggregation pipeline.在 Mongo 4.2 中, <update>文档也可以是一个聚合管道。 Try this one:试试这个:

db.getCollection("C").updateMany(
   {},
   [{
      $set: {
         "d": ["$a"]
      }
   }]
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在MongoDB中找到包含NaN字段的所有文档? - how do I find all documents with a field that is NaN in MongoDB? 在 mongodb 中保存或更新文档时如何防止更新“updatedAt”字段? - how to prevent updating of "updatedAt" field while saving or updating documents in mongodb? 使用_id字段更新mongodb中的多个文档 - Updating multiple documents in mongodb using _id field 在MongoDB PHP中更新嵌套文档中的字段 - Updating field in nested documents in mongodb php 如何使用 MongoDB 将多个文档中的字段转换为对象中的数组? - How do I convert a field from multiple documents into an array in an object with MongoDB? 如何根据 MongoDB 中的另一个数组更新嵌入式文档中的字段 - How do I update a field in embedded documents based on another array in MongoDB 在MongoDB上,如何过滤掉包含字符串数组的字段包含某个字符串的文档? - On MongoDB, how do I filter out documents where a field with an array of strings includes a certain string? 如何找到 mongodb 集合中包含字段/值对的所有文档? - How do I find all documents in mongodb collection that contain field/value pair? 添加文档时是否必须重建MongoDB索引 - Do I have to rebuild MongoDB index when I add documents 当它是 mongodb 中的 object 数组时,我如何更新相同的字段 - How do i update same field when it is array of object in mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM