Goku95
Goku95

Reputation: 71

Fetch mongo documents based on multiple fields

Given mongo document of the following form in a collection:

{
  "_id":"ObjectId",
  "value":{
    "id": 1,
     "payment": [
       {
        "status": {
           "id": "1.1",
           "value": "Paid"
         }
      },
      {
       "status": {
           "id": "1.2",
           "value": "Scheduled"
        }
      },
      {
      "status": {
          "id": "1.3",
          "value": "Recorded"
       }
      }
    ]
  }
}

ids = [1,2,3,4]

How can i fetch all documents having id in ids and at least one of payments.status.value equal to Scheduled state ?

I am using the following query but it's returning 0 records,

db.collectionName.find({$and:[{"value.id":{$in:ids}},{"value.payment.status.value":"Scheduled"}]})`

Upvotes: 0

Views: 295

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

db.collection.find({
    'value.payment': {
        $elemMatch: {
            'status.value': 'Scheduled'
        }
    },
    'value.id': {
        $in: [1, 2, 3, 4]
    }
}, {
    'value.id': 1,
    'value.payment.$.status': 1
})

Upvotes: 0

Ahmed Abdelaal
Ahmed Abdelaal

Reputation: 159

you can specify the name of the collection
so instead of this:

db.collection.find({
    $and:
    [
        {"value.id": {$in:ids}},
        {"value.payment.status.value":"Scheduled"}
    ]
})

you can write:

db.payments.find({
    $and:
    [
        {"value.id":{$in:ids}},
        {"value.payment.status.value":"Scheduled"}
    ]
})

Upvotes: 2

Related Questions