skip to Main Content

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"
}

4

Answers


  1. Try with this.

    db.getCollection('events_or_whatever_u_').find({'_id': ObjectId('xxxxx')})
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
  4. 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})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search