2017-07-11 33 views
0

我想從數組中提取值。 現在我有MongoDB查詢從數組中查找並提取值

db.getCollection('typeE').distinct("list.name",{"list.name":"C"}) 

我有這樣結構

object(1)"list":[{"name":"A","value":10},{"name":"B","value":20},{"name":"C","value":50}] 
object(2)"list":[{"name":"D","value":100},{"name":"E","value":70}] 

欲接收50,但現在接收(1)

我還試圖

db.getCollection('typeE').distinct("list.value",{"list": {$elemMatch: {"name":"C"}}}) 
唯一對象

但它是返回陣列

回答

0

你這樣做是錯誤的。你想要什麼(如果我得到你的權利)是讓子文檔的不同value"name": "C"

你應該試試這個:

db.getCollection('typeE').aggregate([ 
    {$unwind: "$list"}, 
    {$match: { "list.name": "C"}}, 
    {$group: {_id: null, distinctValue: {$addToSet: "$list.value"}}} 
]) 

這將輸出:

{"_id": null, "distinctValue": [ 50 ] } 
+0

謝謝,這是正確的 – Vladimircape