2011-04-13 144 views
3

我收集如下。mongodb阵列中的匹配元素

{ 
"name" : "pqr" , 
"loc" : 
    [ 
    {"area" : "c" , "country" : "d"}, 
    {"area" : "w" , "country" : "r"} 
    ] 
} 

我想使该匹配,使得只有匹配阵列LOC

这意味着如果

  1. 给出面积为c或国家d那么它返回文档的第一个元素。
  2. 给区域为w或国家为r则不会返回元素

只匹配蒙戈阵列

的第一要素是这是可能在蒙戈?

如果有一个人知道PLZ回复

感谢

回答

3

所以,如果你想只返回第一个匹配元素,你应该使用limit(n)和查询这样的:

1.gives面积为c或国家然后它返回文档。

db.items.find({ $or : [ {"loc.area": "c" } , 
         {"loc.country ": "d" } ] }).limit(1); 

2.gives面积为w或国家为r那么如果你想只在嵌套数组,你可以用它做的第一要素来搜索不返回元素

db.items.find({ $or : [ {"loc.area": { "$ne" : "w" } }, 
         {"loc.country": { "$ne" : "r" } } ] }).limit(1); 

位置操作员加入.0. - >loc.0.area

更新:我首先误解了你的问题。现在我看到你在寻找loc.0.area

+0

感谢loc.0.area它的工作原理 – 2011-04-13 10:19:04