MongoDB:如何根据其他字段更新数组元素的字段?
我试图通过使用管道更新来更新MongoDB(4.2)中的数据。困难在于我想根据另一个字段向数组元素添加一个字段。我还想对每个元素都这样做。我知道我可以用Javascript来实现每一个功能,但我想知道是否有更好的方法。这就是我想做的一个例子 之前:MongoDB:如何根据其他字段更新数组元素的字段?,mongodb,mongodb-query,Mongodb,Mongodb Query,我试图通过使用管道更新来更新MongoDB(4.2)中的数据。困难在于我想根据另一个字段向数组元素添加一个字段。我还想对每个元素都这样做。我知道我可以用Javascript来实现每一个功能,但我想知道是否有更好的方法。这就是我想做的一个例子 之前: { "_id" : ObjectId("555555555"), "messages" : [ { "author" : { "userId" : "12345"
{
"_id" : ObjectId("555555555"),
"messages" : [
{
"author" : {
"userId" : "12345",
"name" : "John"
},
"text" : "Any text",
},
{
"author" : {
"userId" : "56789",
"name" : "Jim"
},
"text" : "also text"
}
]
}
之后
我尝试的是:
db.mail.update(
{"_id" : ObjectId("555555555")},
[{ $set: { "messages.$[].author.newId": { $concat: [ "000", "$messages.$[].author.userId"]}}}],
{ multi: true, writeConcern: {w: 0} }
)
有人知道怎么解决这个问题吗?
谢谢这将完成所需的更新
db.test.update(
{ _id : ObjectId("555555555") },
[
{
$set: {
messages: {
$map: {
input: "$messages",
in: {
$mergeObjects: [
"$$this",
{ "author": {
$mergeObjects: [
"$$this.author",
{ newId: { $concat: [ "000", "$$this.author.userId"] } }
]
} }
]
}
}
}
}
}
],
{ multi: true, writeConcern: {w: 0} }
)
请注意,当不使用聚合时,数组更新的所有位置运算符$[]
将与更新操作一起使用。当字段值依赖于文档中的另一个字段时,必须使用聚合进行更新
db.test.update(
{ _id : ObjectId("555555555") },
[
{
$set: {
messages: {
$map: {
input: "$messages",
in: {
$mergeObjects: [
"$$this",
{ "author": {
$mergeObjects: [
"$$this.author",
{ newId: { $concat: [ "000", "$$this.author.userId"] } }
]
} }
]
}
}
}
}
}
],
{ multi: true, writeConcern: {w: 0} }
)