Mohamed Abu Galala
Mohamed Abu Galala

Reputation: 438

Query array by stored index in document in MongoDB

I have a document like this

{
    "status": {
        "current": 0,
        "priority": [{
            "operationName": "PHOTO",
            "status": "WAITING"
        },
        {
            "operationName": "DESIGN",
            "status": "NOTARRIVED"
        },
        {
            "operationName": "COLOR_SEPARATION",
            "status": "NOTARRIVED"
        }]
    }
}

and want to query on data like this

{
    "status.priority.$status.current.operationName": {
        $in: ['SERVICES', 'PHOTO']
    }
}

when I query like this

{
    "status.priority.0.operationName": {
        $in: ['SERVICES', 'PHOTO']
    }
}

it returns the data needed as the 'PHOTO' is the current operation.

I need to query based on an index of the array and this index is stored in the document in status.current

any hint?

UPDATE After question solved I want to optimize it.

Upvotes: 1

Views: 73

Answers (2)

Aabid
Aabid

Reputation: 941

For this you need to use aggregation

db.collname.aggregate([{
    "$project": {
      "_id": 1,
      priority: { $arrayElemAt: ["$status.priority", '$status.current'] },
    }
  },
  {
    $match: {
      "priority.operationName": {
        $in: ['DESIGN', 'COLOR_SEPARATION', 'PHOTO']
      }

    }
  }
])

This will work for you.

Result will be like

{
    "_id" : ObjectId("5b6b656818883ec018d1542d"),
    "priority" : {
        "operationName" : "PHOTO",
        "status" : "WAITING"
    }
}

Upvotes: 1

s7vr
s7vr

Reputation: 75914

You can use $arrayElemAt with $expr in 3.6.

Something like

db.colname.find(
 {"$expr":{
   "$in":[
     {"$arrayElemAt":["$status.priority.operationName","$status.current"]},
     ['DESIGN', 'COLOR_SEPARATION', 'PHOTO']
   ]
 }}
)

Upvotes: 2

Related Questions