2016-03-06 124 views
0

我想查詢一個用戶集合與多個嵌套對象,我不知道如何正確使用投影操作符(例如$),因爲他們似乎爲數組而不是對象工作。在MongoDB中查詢嵌套對象

每個用戶都有一個「booksRecords」對象,具有多個書對象(例如hc_1_3,hc_1_4等)。每個圖書對象都有一個名爲currLevel的字段,我試圖找到至少有一個圖書對象currLevel:'nursery'的孩子。

我試過 User.find({'booksRecords。$。currLevel':'nursery'}),但這似乎並沒有工作,我想知道什麼是正確的方式來查詢嵌套的對象?

我檢查了Querying nested in mongoDB,但它與我的情況不同,因爲我在查詢嵌套對象。

[ 
    //first object 
    { 
    _id: "xxx", 
    booksRecords: { 
     hc_1_3: { 
     markedRead: false, 
     currLevel: "elementary" 
     }, 
     hc_1_2: { 
     markedRead: false, 
     currLevel: "elementary" 
     } 
    } 
    }, 
    //second object 
    { 
    _id: "xyz", 
    booksRecords: { 
     hc_1_3: { 
     markedRead: false, 
     currLevel: "elementary" 
     }, 
     hc_1_2: { 
     markedRead: false, 
     currLevel: "nursery" 
     } 
    } 
    } 
] 

回答

1

$ projection僅適用於數組。 您需要使用$where來評估每個文檔:

db.User.find({ $where: function() { 
    for (var i=0 in this.booksRecords) { 
     if (this.booksRecords[i].currLevel === 'nursery') { 
      return true; 
     } 
    } 
    return false; 
} }); 
0

可以請這個:

var userList = db.User.find(); 
var booksRecordsList={}; 

while(userList.hasNext()){ 
    var user = userList.next(); 
    for(var key in user.booksRecords){ 

     if (!(key in booksRecordsList)) { 
     booksRecordsList[key] = key; 
     } 
    } 
}; 

db.User.find().forEach(function(doc){ 
    for (var booksRecord in booksRecordsList){ 
     var booksRecordItem = doc.booksRecords[booksRecord]; 
     if(booksRecordItem.currLevel == "nursery"){ 
      print(tojson(doc)); 
     } 
    } 
});