开发者

match element in array of mongodb

开发者 https://www.devze.com 2023-02-25 18:28 出处:网络
I have collection as follows . { \"name\" : \"pqr\" , \"loc\" : [ {\"area\" : \"c\" , \"country\" : \"d\"},

I have collection as follows .

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

I want to make which match such that only match the first element of array loc

that means if

  1. gives area as c or country d then it return document.
  2. gives area as w or country as r the开发者_如何学Pythonn does not return element

only match first element of mongo array

Is this possible in mongo ?

if some one knows plz reply

Thanks


So if you want return only first matched element you should use limit(n) and queries like this:

1.gives area as c or country d then it return document.

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

2.gives area as w or country as r then does not return element

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

If you want to search only in the first elements of nested array you can do it using positional operator by adding .0. -> loc.0.area.

Update: I've misunderstand your question first. Now i see that you looking for loc.0.area.

0

精彩评论

暂无评论...
验证码 换一张
取 消