2014-11-21 56 views
0

如何查詢僅返回來自房間的學生:年齡> 18歲的學生? 我想得到這樣的輸出:使用mongodb從列表中查詢對象

{ 
     "name": "john", 
     "age": 21, 
     "books": [ 
       { 
       "title": "algebra", 
       "pages": 300, 
       "author": "Jkrowling" 
       } 
      ] 
     } 

和文件如下

{ 
"teacher": "teachername", 
"room": 102, 
"students": [ 
     { 
     "name": "john", 
     "age": 21, 
     "books": [ 
       { 
       "title": "algebra", 
       "pages": 300, 
       "author": "Jkrowling" 
       } 
      ] 
     } 
    ] 
}  

回答

0

在聚集將有助於

db.collectionName.aggregate({"$unwind":"$students"}, 
    {"$match":{"room":102,"students.age":{"$gt":18}}}).pretty() 
+0

任何非集合的方式來做到這一點? – vmr 2014-11-21 06:06:52

+0

如果學生數組只有單個值,那麼可以使用下面的查詢'db.collectionName.find({「room」:102,「students.age」:{「$ gt」:18}})。pretty()'或如果stiudents包含更多的價值,然後使用聚合 – Yogesh 2014-11-21 06:09:30