Home > Net >  How to find Object inside array in mongoose?
How to find Object inside array in mongoose?

Time:01-18

This is how the database looks like

[
//document1
    {
        "email": "[email protected]",
        "cart": [
            {
                "id": 4,
                "name": "Pen",
            }
        ]
    },
//document2
    {
        "email": "[email protected]",
        "cart": [
            {
                "id": 42,
                "name": "Ball",
            }
        ]
    }
]

How to write mongoose query to find the Item inside cart in a particular document using Email. For example, I need the item with id 4 which is in the cart of the document with the email "[email protected]"

  1. find a document with email "[email protected]"
  2. Inside the document in the cart array find the item with id "4"

CodePudding user response:

You can try running this query

  db.collection.find({
  email: "[email protected]",
  cart: {
    $elemMatch: {
      id: 4
    }
  }
})

I have first queried it using the email address. Then in the array I have used elemMatch to get the obj matching the id

  •  Tags:  
  • Related