2017-04-16 66 views
1

的計數我的數據是這樣的:貓鼬findOne返回對象的子陣列

{ 
    "profileID": "123456789", 
    "myArray": [ 
    { 
     "read": false 
    }, 
    { 
     "read": true 
    }, 
    { 
     "read": false 
    }, 
    { 
     "read": true 
    } 
    ] 
} 

我希望能夠得到的計數:myArray的其中。我需要在貓鼬上做這個。在上面的例子中,我想要的回報是。

我findOne是象下面這樣:

userModel.findOne({'profileID': 123456789}, function(err, myArray) { 
    //Code to run here 
}); 

我可以通過響應手動運行,讓我計數方式,但,這將是非常ineffeciant。

如何在數據庫級別獲得用戶的未讀取數值myArray的

感謝

回答

2

你應該使用aggregate

> db.bla.insert({ 
... "profileID": "123456789", 
... "myArray": [ 
...  { 
...  "read": false 
...  }, 
...  { 
...  "read": true 
...  }, 
...  { 
...  "read": false 
...  }, 
...  { 
...  "read": true 
...  } 
... ] 
... }) 
WriteResult({ "nInserted" : 1 }) 

> db.bla.aggregate([{$match:{"profileID":"123456789"}}, {$unwind:"$myArray"}, {$match:{"myArray.read":false}}, {$count:"unread_mail"}]) 
{ "unread_mail" : 2 } 

然後,您可以$unwind您的陣列做你的計數。

+1

就像一個魅力的伴侶!最初我遇到了** $ count **的問題,但後來我查找了Mongo的文檔,它是在3.4版本中引入的,而我在3.2.x版本中進行升級,所以升級後都很好。謝謝! –

0

您不能使用findOne過濾期望多個匹配的數組。

您可以在聚合查詢中使用$filter$size

下面的查詢將$filtermyArray其中read是假的,然後$size計數的篩選項目

db.collection.aggregate(
    { $match: { profileID: "123456789" } }, 
    { $project: {size: { $size: { $filter: { input: "$myArray", as: "result", cond: { $eq: ["$$result.read", false] } } } } } } 
)