Andy Refuerzo
Andy Refuerzo

Reputation: 3332

Nested $and or grouped $and in MongoDB

Consider the following document:

{
    "_id" : ObjectId("5130f9a677e23b11503fee55"),
    "ItemType" : "Bicycle"
     "Attributes" : [{
         "AttributeName" : "Spare Tire",
         "AttributeValue" : "1"
     }, {
         "AttributeName" : "With helmet?",
         "AttributeValue" : "0"
     }, {
         "AttributeName" : "Number of Locks",
         "AttributeValue" : "1"
     }]
}

How do I write the query to get bicycles with spare tire and no helmet?

I tried the following but it doesn't give me what I want.

{ 
"$and" : 
[ 
    { "ItemType" : "Bicycle" }, 
    { "$and": 
        [{ "Attributes.AttributeName" : "With helmet?" }, 
         { "Attributes.AttributeValue" : "0" }
   ]},
    { "$and": 
        [{ "Attributes.AttributeName" : "Spare Tire" }, 
         { "Attributes.AttributeValue" : "1" }
   ]}
]}

It seems that as long as there is a value that matches Attributes.AttributeValue - regardless of the accompanying Attributes.AttributeName - then it returns that document. It's like having this query:

{ 
"$and" : 
[ 
    { "ItemType" : "Bicycle" },                        //true
    { "Attributes.AttributeName" : "With helmet?" },   //true 
    { "Attributes.AttributeName" : "Spare Tire" },     //true
    { "Attributes.AttributeValue" : "0" },             //any
    { "Attributes.AttributeValue" : "1" }              //any
]}

Upvotes: 0

Views: 983

Answers (1)

Sammaye
Sammaye

Reputation: 43884

I believe you are looking for $elemMatch here, whereby it makes sure that the correspoding AttributeName and AttributeValue are in the same element of a multi-value field ( http://docs.mongodb.org/manual/reference/operator/elemMatch/ ):

{
    ItemType: 'Bicycle', 
    $and:[
        {"Attributes": {$elemMatch:{AttributeName: 'With helmet?', AttributeValue: 0 }}},
        { //Next match }
    ]
}

Try something like that

Upvotes: 3

Related Questions