Created
July 29, 2017 16:31
-
-
Save WillieYang/0b29e25b0eb881aa267f35b68ed486ba to your computer and use it in GitHub Desktop.
How to find a particular subdocument in a document by condition?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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