我是 MongoDB 的新手。我有一個包含多個檔案的集合,其中特定檔案具有嵌套陣列結構。我需要遍歷這個嵌套陣列并更改被迭代欄位的值的資料型別。
嵌套陣列結構:
[
{
"identifier":{
"type":"xxxx",
"value":"1111"
},
"origin":"example.com",
"score":8.0
},
{
"identifier":{
"type":"yyyyy",
"value":"222"
},
"origin":"example.com",
"score":8.0
},
{
"identifier":{
"type":"zzzzz",
"value":"3333"
},
"origin":"https://olkdghf.com",
"score":8.0
}
]
問題是我需要更改資料型別而不替換現有欄位值。但我得到一個新的空值而不是原始值。
我的查詢:
db.SourceEntityv8test.find({"hasIdentifier.identifier.type": {$exists:true}}).sort({_id:1}).skip(0).limit(100).forEach(function(x)
{
db.SourceEntityv8test.update({_id: x._id}, {$set:{"hasIdentifier.$[].identifier.type":[]}} );
});
預期輸出:
[
{
"identifier":{
"type":[xxxx],
"value":"1111"
},
"origin":"example.com",
"score":8.0
},
{
"identifier":{
"type":[yyyyy],
"value":"222"
},
"origin":"example.com",
"score":8.0
},
{
"identifier":{
"type":[zzzzz],
"value":"3333"
},
"origin":"example.com",
"score":8.0
}
]
實作輸出:
[
{
"identifier":{
"type":[],
"value":"1111"
},
"origin":"example.com",
"score":8.0
},
{
"identifier":{
"type":[],
"value":"222"
},
"origin":"example.com",
"score":8.0
},
{
"identifier":{
"type":[],
"value":"3333"
},
"origin":"example.com",
"score":8.0
}
]
uj5u.com熱心網友回復:
有點復雜。期望您需要通過使用聚合管道進行更新來實作它。
概念:
- 通過1.1更新整個
hasIdentifier陣列。
1.1。hasIdentifier將陣列中的每個檔案與1.1.1合并。
1.1.1。identifier將物件與帶有type陣列的檔案合并。
db.SourceEntityv8test.update({_id: x._id},
[
{
$set: {
hasIdentifier: {
$map: {
input: "$hasIdentifier",
in: {
$mergeObjects: [
"$$this",
{
"identifier": {
$mergeObjects: [
"$$this.identifier",
{
type: [
"$$this.identifier.type"
]
}
]
}
}
]
}
}
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437028.html
標籤:数组 json mongodb 目的 mongodb查询
