Ankit
Ankit

Reputation: 540

Find field inside an array using $elemMatch

I have a invoice collection, in which I want find the document with a specified book's id.

  db.invoice.find({"sold": {$elemMatch: {"book":{$elemMatch:{"_id":"574e68e5ac9fbac82489b689"}}}}})

I tried this but it didn't work

{
    "_id" : ObjectId("575e9bf5576533313ac9d993"),
    "sold" : [
        {
            "book" : {
                "_id" : "574e68e5ac9fbac82489b689",
                "price" : 100,
            },
            "quantity" : 10,
            "total_price" : 1000
        }
    ],
    "date" : "13-06-2016"
}

Upvotes: 3

Views: 885

Answers (2)

Sede
Sede

Reputation: 61225

You do not need the $elemMatch query operator here because you only specify only a single query condition.

db.invoice.find( { 'sold.book._id': '574e68e5ac9fbac82489b689' } )

This is mentioned in the documentation:

If you specify only a single condition in the $elemMatch expression, you do not need to use $elemMatch

Upvotes: 3

Shawyeok
Shawyeok

Reputation: 1238

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

mongo> db.invoice.find({"sold": {$elemMatch: {"book._id":"574e68e5ac9fbac82489b689"}}}).pretty()
{
    "_id" : ObjectId("575e9bf5576533313ac9d993"),
    "sold" : [
        {
            "book" : {
                "_id" : "574e68e5ac9fbac82489b689",
                "price" : 100
            },
            "quantity" : 10,
            "total_price" : 1000
        }
    ],
    "date" : "13-06-2016"
}

Upvotes: 0

Related Questions