2016-12-06 32 views
1

我的文件是這樣的:如何從子數組中提取所有子元素?

// collection: photos 
{ 
    "_id" : ObjectId("5835840fb6ca90e020020b22"), 
    "customerIds" : [ 
     { 
      "code" : "SHDR327D7DVKHBT3", 
      "cType" : "photoPass", 
      "userIds" : ['aaa','bbb'] 
     }, 
     { 
      "code" : "SHDR327D7DVKHBT3", 
      "cType" : "photoPass", 
      "userIds" : ['ddd','aaa','ccc'] 
     } 
    ] 
} 

customerIds兩個文件是相同的。現在我想從userIds中刪除所有'aaa',我怎樣才能在一個命令中實現這一點?

我用這個命令刪除它們,但一次只能刪除一個。

db.photos.update(
     {"customerIds.code":'SHDR327D7DVKHBT3',"customerIds.userIds":'aaa'}, 
     {$pull: {"customerIds.$.userIds":{$in:['aaa']}}}, 
     { multi: true,upsert: false} 
) 

回答

0

這是你想要做的嗎?

db.testCollection.aggregate([ 
    {$unwind: "$customerIds"}, 
    {$unwind:"$customerIds.userIds"}, 
    {$match:{"customerIds.userIds":"aaa"}}, 
    {$project:{"customerIds.userIds":1,_id:0}} 
]) 

這將返回你的「AAA」:

{ 
     "_id" : ObjectId("584708e6888ff31225c2e375"), 
     "customerIds" : { 
       "userIds" : "aaa" 
     } 
} 
{ 
     "_id" : ObjectId("584708e6888ff31225c2e375"), 
     "customerIds" : { 
       "userIds" : "aaa" 
     } 
} 
+0

謝謝你回答我的問題,但其實我想知道的是如何刪除他們... –

相關問題