Search code examples
mongodbmongodb-querypymongonosql-aggregation

Search for an object with a specific value in an array in MongoDB


I have an array of objects in my document which resides in a collection in MongoDB. And, it looks like the following

"tracking": [{
    "track_id" : "abcd",
    "timestamp" : 1604581360,
    "status" : "approved",
    "category" : "containers",
    "time_of_activity" : "23:11",
    "date_of_activity" : "03-Oct-20"
}, {...}, ...] 

I want to search for an object on this array where the track_id of the object is abcd

I am having a hard time writing a Mongo Aggregation for the same. Can anyone please show me a way, to how this can be achieved using a Mongo Aggregation query?


Solution

  • You can query embedded documents inside an array using find as below:

    db.collection.find({"tracking.track_id": "abcd"})

    Playground