2015-05-26 46 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}] –