Praveen Gehlot
Praveen Gehlot

Reputation: 364

MongoDB: How to find with whole array

I'm new on MongoDB.

I want to find document with matching of whole array.

let show you collection schema. here is combination collection data

{
   _id: 741258,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' },
                 { attr_id: 456, val: 'Blue' },
                 { attr_id: 789, val: 'Slim' } ],
},
{
   _id: 745896,
   product_id: 258,
   attributes: [ { attr_id: 124, val: '28' },
                 { attr_id: 484, val: 'Red' },
                 { attr_id: 852, val: 'Small' } ],
},
{
   _id: 985632,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' },
                 { attr_id: 456, val: 'Blue' } ],
},
{
   _id: 456855,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' } ],
}

Query :


db.combination.find( { product_id: "258" },
                 { attributes: { $elemMatch: [ { attr_id: 123, val: '26' },
                                               { attr_id: 456, val: 'Blue' } 
                                             ] } } )

Error :


(node:4460) UnhandledPromiseRejectionWarning: MongoError: $elemMatch needs an Object

Expected Result :


{
   _id: 985632,
   product_id: 258,
   attributes: [ { attr_id: 123, val: '26' },
                 { attr_id: 456, val: 'Blue' } ],
},

Please help to slow this issue. Thanks in advance

Upvotes: 0

Views: 70

Answers (1)

Ali Husseinat
Ali Husseinat

Reputation: 116

You don't need to use $elemMatch, the solution is much more simpler.

For an exact match on an array you just need to specify the hole array to match.

For example, to achieve the expected result you just need to query:

db.collection.find({
  attributes: [
    {
      attr_id: 123,
      val: "26"
    },
    {
      attr_id: 456,
      val: "Blue"
    }
  ]
})

Just be aware that it needs to be exactly the same, if you swap the order of attributes inside any object your query will not match the desired document.

For example, the following query will not return the desired document:

db.collection.find({
  attributes: [
    {
      attr_id: 123,
      val: "26"
    },
    {
      val: "Blue", // swaped attributes order
      attr_id: 456
    }
  ]
})

For more information on how to query nested arrays, visit this documentation page.

Upvotes: 1

Related Questions