[英]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.