3

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"
}
styvane
  • 49,879
  • 15
  • 119
  • 132
Ankit
  • 500
  • 4
  • 21

2 Answers2

3

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

styvane
  • 49,879
  • 15
  • 119
  • 132
0

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"
}
萧易客
  • 1,036
  • 8
  • 15
  • 1
    I think the query is still using `$elemMatch` unnecessarily. Just `{'sold.book._id': '574e68e5ac9fbac82489b689'}` query will work fine. – Shrabanee Jun 14 '16 at 08:08