D. *_* L. 5 javascript arrays object mongodb
如何将数组转换为 MongoDB 中的对象?
例如,我想转换这个文档:
{
"_id" : NumberLong(279),
"userAddressList" : [
{
"street" : "Street",
"house" : "House",
"building" : "Building",
"flat" : NumberLong(0),
"entrance" : NumberLong(0),
"floor" : NumberLong(0),
"intercom" : "Intercome"
}
],
}
Run Code Online (Sandbox Code Playgroud)
对此:
{
"_id" : NumberLong(279),
"userAddressList" :
{
"street" : "Street",
"house" : "House",
"building" : "Building",
"flat" : NumberLong(0),
"entrance" : NumberLong(0),
"floor" : NumberLong(0),
"intercom" : "Intercome"
},
}
Run Code Online (Sandbox Code Playgroud)
所以我需要转换""userAddressList" : [{..}]"为""userAddressList" : {..}".
对于 MongoDB 4.2 及更高版本
您可以尝试以下在更新中使用聚合管道的查询:
db.collection.updateMany(
{},
[
{ '$addFields': {
'userAddressList': {
'$arrayElemAt': ['$userAddressList', 0]
}
} }
]
)
Run Code Online (Sandbox Code Playgroud)
对于较旧的 MongoDB 版本:
db.collection.find().forEach(function(doc){
userAddressList = doc.userAddressList[0];
doc.userAddressList = userAddressList;
db.collection.save(doc);
})
Run Code Online (Sandbox Code Playgroud)
或使用运行以下管道的聚合框架
db.collection.aggregate([
{ "$addFields": {
"userAddressList": {
"$arrayElemAt": ["$userAddressList", 0]
}
} },
{ "$out": "collection" }
])
Run Code Online (Sandbox Code Playgroud)
请注意,这不会更新您的集合,而是替换现有集合,并且不会更改上一集合中存在的任何索引。如果聚合失败,该$out操作不会对预先存在的集合进行任何更改。
| 归档时间: |
|
| 查看次数: |
3441 次 |
| 最近记录: |