2015-05-26 41 views
0

我有一個包含以下信息的收集MongoDB的:限制查詢到現場和陣列投影

{ 
    "_id" : 1, 
    "info" : { "createdby" : "xyz" }, 
    "states" : [ 11, 10, 9, 3, 2, 1 ]} 
} 

我通過查詢

db.jobs.find({},{states:1}) 

然後我得到的只有美國僅投影狀態(和全狀態值數組)!或者我可以

db.jobs.find({},{states : {$slice : 1} }) 

只選擇一個陣列中的狀態,然後我得到的只有一個狀態值,但與文檔中的所有其他領域以及沿。

有沒有辦法只選擇「州」字段,同時只能切片數組中的一個元素。當然,我可以排除領域,但我想有一個解決方案,我可以在其中指定兩個條件。

+1

['aggregation'(http://docs.mongodb.org/manual/meta/aggregation-quick-reference/)是你的朋友。 '$ unwind'狀態;使用'$ match'來過濾和'$ project'來重塑或排除字段 – styvane

+0

你可以發佈你的預期輸出嗎? – Yogesh

+0

@yogesh期望的輸出應該只包含只有一個數組值的「狀態」。 –

回答

1

您可以通過兩種方式來實現:

1>使用mongo projection

<field>: <1 or true> Specify the inclusion of a field

<field>: <0 or false> Specify the suppression of the field

讓你的查詢作爲

使用3210

2>其他方式mongo aggregation

db.jobs.aggregate({ 
    "$unwind": "$states" 
    }, { 
    "$match": { 
     "states": 11 
    } 
    }, // match states (optional) 
    { 
    "$group": { 
     "_id": "$_id", 
     "states": { 
     "$first": "$states" 
     } 
    } 
    }, { 
    "$project": { 
     "_id": 0, 
     "states": 1 
    } 
    }) 
+0

我使用聚集來包含[{$ project:「states」},{$ unwind:「states」},{$ limit:1}] –