0

I need to get all documents that match an array of objects or an object with many fields.

Example 1 (array of objects) If the document match the country_code than he must have one of postal_codes too

var locations = [
  {
    country_code : 'IT',
    postal_codes : [21052, 21053, 21054, 21055]
  },
  {
    country_code : 'GER',
    postal_codes : [41052, 41053, 41054, 41055]
  }
]

Example 2 (object with fields) If the document match the key than it must have one of the values of that key

var location = {
  'IT' : [21052, 21053, 21054, 21055],
  'GER' : [41052, 41053, 41054, 41055]
}

I like the first type of document to match(array of objects) but how can i use to get all documents that match?

The documents to find have this structure:

{
  "_id" : ObjectId("587f6f57ed6b9df409db7370"),
  "description" : "Test description",
  "address" : {
      "postal_code" : "21052",
      "country_code" : "IT"
   }
 }

2 Answers 2

0

You can use $in to find such collections.

db.collection_name.find(
                     { address.postal_code: { $in: [your values] } },
                   )

Check this link for querying child objects. Check this link for mongoDB $in

1
  • You can add multiple conditions as required to achieve the results.
    – balaaagi
    Jan 20, 2017 at 13:12
0

One way is to use the $or operator. This will help you limit the combinations of country_code and postal_code.

Your query should look something like this.

db.locations.find({
    $or: [{
        "country_code": "IT",
        "postal_code": {
            $in: [21052, 21053, 21054, 21055]
        }
    }, {
        "country_code": "GER",
        "postal_code": {
            $in: [41052, 41053, 41054, 41055]
        }
    }]
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.