Search code examples
mongodbmongo-scala-driver

match element in array of mongodb


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 then does not return element

only match first element of mongo array

Is this possible in mongo ?

if some one knows plz reply

Thanks


Solution

  • 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.