mongodb - MongoDB:如何根据其他字段更新数组元素的字段?
问题描述
我正在尝试通过使用带有管道的更新来更新我的 MongoDB (4.2) 中的数据。困难在于我想根据另一个字段向数组元素添加一个字段。我也想对每个元素都这样做。我知道我可以用 Javascript 来做每一个,但我想知道是否有更好的方法。所以这就是我想要做的一个例子
前:
{
"_id" : ObjectId("555555555"),
"messages" : [
{
"author" : {
"userId" : "12345",
"name" : "John"
},
"text" : "Any text",
},
{
"author" : {
"userId" : "56789",
"name" : "Jim"
},
"text" : "also text"
}
]
}
后
{
"_id" : ObjectId("555555555"),
"messages" : [
{
"author" : {
"userId" : "12345",
"name" : "John",
"newId" : "00012345"
},
"text" : "Any text",
},
{
"author" : {
"userId" : "56789",
"name" : "Jim",
"newId" : "00056789"
},
"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} }
)
请注意,$[]
当不使用聚合时,数组更新的所有位置运算符将与更新操作一起使用。当字段值依赖于文档中的另一个字段时,您必须使用聚合来更新。
推荐阅读
- python - 将列合并为一行并将列值转换为新列 pandas
- python - 在python中解析大量的JSON数据
- python - Python:如何按部分查找列表中的索引?
- google-cloud-functions - 在 Google Functions 中处理 Pubsub 消息
- node.js - 在 AWS windows 服务器上部署 nodejs express
- python - 如何使用 Python cv2 包测量中心角
- ios - 如何在 Swift 中的 UITableViewController 上放置一个按钮
- python - 使用 TensorFlow 数据集的验证集
- python-3.x - Transferlearning ResNet 模型不学习
- r - dplyr `across()` 函数需要 `rowwise()` 函数是吗?