Anup
Anup

Reputation: 635

MongoDB: geospatial query with additional conditions

{ _id : ObjectId(...),
  name : "...",
  addresses : [ {
                 context : "home" ,
                 loc : [ 55.5, 42.3 ]
                } ,
                {
                 context : "office",
                 loc : [ -74 , 44.74 ]
                }
              ]
}

address.loc is "2d" indexed.

I want to write a query that should give me all the document that are $near a location and the context is office.

I wrote some thing like:
   db.coll.find({'address.loc':{$near:[lat,lng]}, 'address.context' : "office"});

Above query doesn't give me results that wanted. It searches for location in the entire "Address" array and then searches for context in the entire array.

I would like to search for same array location and same context. I know it could be done by $elemMatch but when I try to use it, it says there is no 2d index available or 2dsphere index.

I am new to MongoDB and not sure how should I write my query.

Upvotes: 0

Views: 297

Answers (1)

pilliq
pilliq

Reputation: 324

I've tried the query and it seems to work as you intend with the $elemMatch operator. I think the problem is that you have a typo in your query where address is used instead of addresses. Your query should look like:

db.coll.find({ 'addresses.loc':{$near:[lat,lng]}, addresses: { $elemMatch: {context: "office"} } });

Upvotes: 4

Related Questions