Home > OS >  How to find specific object from array in MongoDB
How to find specific object from array in MongoDB

Time:05-31

Suppose I have this MongoDB document:

{
  "_id": {
    "$oid": "628f739398580cae9c21b44f"
  },
  "place":"Amsterdam",
  "events": [
    {
      "eventName": "Event one",
      "eventText": "Event",
      "eventDate": "010101"
      "host":"Bob"
    },
    {
      "eventName": "E2",
      "eventText": "e2",
      "eventDate": "020202"
      "host":"John"
    }
  ]
}

{
  "_id": {
    "$oid": "628f739398580cae9c21b44f"
  },
  "place":"London",
  "events": [
    {
      "eventName": "e3",
      "eventText": "e3",
      "eventDate": "010101",
      "host":"Bob"
    }
  ]
}

And I want to get the array block of events being hosted by Bob, how would I do that? I have tried to use $elemSelector like this:

const result = await mongoDatabase
      .collection("temp")
      .find({ events: { $elemMatch: { eventName: "E2" } } })
      .toArray();

    console.log(JSON.stringify({ result }));

But it just returns all events at the same place as the selected, Amsterdam in this case.

Wanted result:

{
  "eventName": "Event one",
  "eventText": "Event",
  "eventDate": "010101"
  "host":"Bob"
},
{
  "eventName": "e3",
  "eventText": "e3",
  "eventDate": "010101",
  "host":"Bob"
}

CodePudding user response:

Check this out

db.collection.aggregate({
  $unwind: "$events"
},
{
  $match: {
    "events.host": "Bob"
  }
},
{
  "$project": {
    "events": 1,
    "_id": 0
  }
},
{
  "$replaceRoot": {
    "newRoot": "$events"
  }
})

And you can play around with more test data here: https://mongoplayground.net/p/A1UbZdZgZmr

CodePudding user response:

You can achieve with simple pipeline stages

db.collection.aggregate([
  {
    "$match": {//Match
      "events.host": "Bob"
    }
  },
  {
    "$project": {
      "e": {
        "$filter": {//Filter matching elements
          "input": "$events",
          "as": "event",
          "cond": {
            "$eq": [
              "$$event.host",
              "Bob"
            ]
          }
        }
      }
    }
  }
])

Playground

CodePudding user response:

Following Structure can be achieved by using projection query in MongoDB one lucid solution for the above can be this

 db.collection("temp").find({ "events":{ $elemMatch:{ "eventName":"e3" }  } }, {"events":1,"_id":0})

CodePudding user response:

Try with this.

db.getCollection('events_or_whatever_u_').find({'_id': ObjectId('xxxxx')})
  • Related