使用字段的值并将其添加到数组中的新字段 - Mongodb
我正在尝试将其变成
{
"fooList" : [
{
"bar" : {
"baz" : 100
}
},
{
"bar" : {
"baz" : 200
}
}
]
},
{
"fooList" : [
{
"bar" : {
"baz" : 300
}
},
{
"bar" : {
"baz" : 400
}
}
]
}
这样:
{
"fooList" : [
{
"baz" : 100,
"bar" : {
"baz" : 100
}
},
{
"baz" : 200,
"bar" : {
"baz" : 200
}
}
]
},
{
"fooList" : [
{
"baz" : 300,
"bar" : {
"baz" : 300
}
},
{
"baz" : 400,
"bar" : {
"baz" : 400
}
}
]
}
如您所见,我实际上只是将 baz
及其值从 bar
中复制出来,但我的问题是发生在数组内。
db.getCollection(<collection_name>).updateMany(
{},
{ $set: { 'fooList.$[element].baz' : '$fooList.$[element].bar.baz' } },
{ upsert: true ,
arrayFilters: [{'element.bar' : { $exists : true }}]
}
)
但这只会将字符串 $fooList.$[element].bar.baz
设置为 baz,通过结果可以看到这里
[
{
"_id": ObjectId("5a934e000102030405000000"),
"fooList": [
{
"bar": {
"baz": 100
},
"baz": "$fooList.$[element].bar.baz"
}
]
}
]
有人可以告诉我我可能做错了什么,或者这是否可能?谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在 mongoDB 4.2+ 的更新中使用聚合管道来完成此操作,如下所示:
解释:
playground
不幸的是,当您将更新与聚合管道一起使用时,数组过滤器是不可能的......
对于早期的 mongodb 版本,它看起来像这样:
You can do it using aggregation pipeline in the update in mongoDB 4.2+ as follow:
Explained:
playground
Unfortunatelly arrayFilters are not possible when you use update with aggregation pipeline ...
For earlier mongodb versions it will look something like this:
这是一个变体,演示了 v4.4“合并到自身”功能,该功能将
聚合
转换为更新
。当您想要处理所有文档时,这是一种有用的方法,因为它消除了{}
) 和{multi:true}
位>更新。Here is a variation that demonstrates the v4.4 "merge onto self" capability that turns
aggregate
into anupdate
. This is a useful approach when you want to process all the docs because it eliminates the "no filter" ({}
) and{multi:true}
bits required forupdate
.