Skip to content

Instantly share code, notes, and snippets.

@WillieYang
Created July 29, 2017 16:31
Show Gist options
  • Select an option

  • Save WillieYang/0b29e25b0eb881aa267f35b68ed486ba to your computer and use it in GitHub Desktop.

Select an option

Save WillieYang/0b29e25b0eb881aa267f35b68ed486ba to your computer and use it in GitHub Desktop.
How to find a particular subdocument in a document by condition?
// example when using _id as a query condition
// need to utilize the $element and $ (Positional projection)
> db.users.find({"_id": ObjectId("5974c986dea685349a68242a"), 'userLocation': {"$elemMatch": {'locationName': "Uni Kebab"}}}, {"userLocation.$": 1}).pretty();
{
"_id" : ObjectId("5974c986dea685349a68242a"),
"userLocation" : [
{
"locationName" : "Uni Kebab",
"locationAddress" : "190 Burgess Road, Southampton",
"place_id" : "ChIJ2WK8mvNzdEgRyilaQFDCp1M",
"coords" : [
-1.3924609,
50.9382747
],
"_id" : ObjectId("597b8a68766520512f8ad76c"),
"createdOn" : ISODate("2017-07-28T19:03:04.501Z")
}
]
}
// example when using other filed as a query string
> db.users.find({"email": "Alice@gmail.com", 'userLocation': {"$elemMatch": {'locationName': "Uni Kebab"}}}, {"userLocation.$": 1}).pretty();
{
"_id" : ObjectId("5974c986dea685349a68242a"),
"userLocation" : [
{
"locationName" : "Uni Kebab",
"locationAddress" : "190 Burgess Road, Southampton",
"place_id" : "ChIJ2WK8mvNzdEgRyilaQFDCp1M",
"coords" : [
-1.3924609,
50.9382747
],
"_id" : ObjectId("597b8a68766520512f8ad76c"),
"createdOn" : ISODate("2017-07-28T19:03:04.501Z")
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment