Reputation: 3621
I have the following data in mongodb:
[
{
_id: '1',
address: "64th St and 5th Ave, New York, NY 10021, United States",
location: {
lat: 40,
lng: -73
}
},
{
_id: '2',
address: "108 Cobb Avenue, Elmsford, NY, Estados Unidos",
location: {
lat: 40,
lng: 65
}
},
{
_id: '3',
address: "78 Cobb Avenue, Elmsford, NY, Estados Unidos",
location: {
lat: 41,
lng: -73
}
}
]
I also have the following locations array which I need to search for in the collection:
[
{latitude: 40, longitude: -73},
{latitude: 55, longitude: -73},
]
What I want the query to find is only the item with _id '1' because it matches both latitude and longitude of the same element in the search criteria.
I initially thought about using $in but I need to match two fields in the array, also thought about $elemMatch, but I'm not sure how this fits in. I thought about splitting the latitude and longitude searched for into two separate arrays and using $in on both but then I might match elements which fit only one of the pair in separate query locations (because it's not guaranteed that the match will be in the same array position).
Anyone have any insight on how to build this query w/o resorting to hacks such as adding a third field which is a concatenation of the two and searching for it using $in?
Upvotes: 1
Views: 53
Reputation: 34591
$in
works just fine. Just make sure that the fields (lat
and lng
) are named the same as in your data, and that they are listed in the exact same order. $in
will check that the whole location
document corresponds to at least one document in the passed array.
db.locations.find({
location: {
$in: [
{ lat: 40, lng: -73 },
{ lat: 55, lng: -73 }
]
}
})
Upvotes: 1