简体   繁体   中英

Find MongoDB documents field value by using other field value as key

Sample document :

{
  key: "search",
  phaseStatus: {
    search: "Finish",
    write: "Ongoing"    
  }
}

And I would like to search how many document's phaseStatus is "Finish", which phase is decided by "key".

Such as this document, the key is "search", so i want to query "phaseStatus.search". If another document's key is "write", it will query "phaseStatus.write".

I am trying by $filter , but it expression must a array. I also try like it:

collection.aggregations([{
  $match: {
    "phaseStatus.$key": "Finish"
  }
}])

But did not work. How can I query dynamic field ?

You can try below query :

Query :

db.collection.aggregate([
    {
        $addFields: {
            phaseStatus: {
                $arrayElemAt: [ // As filter returns an array of object, get first object out of an array 
                    {
                        $filter: {
                            input: { // Converted phaseStatus into an array of objects[{k: key, v : value}]
                                $objectToArray: "$phaseStatus"
                            },
                            cond: { // Match the object which has k = $key's value
                                $eq: [
                                    "$$this.k",
                                    "$key"
                                ]
                            }
                        }
                    },
                    0
                ]
            }
        }
    },
    {
        $addFields: {
            phaseStatus: "$phaseStatus.v" // get the value of v field from phaseStatus object & assign it to phaseStatus field
        }
    },
    {
        $match: {
            phaseStatus: "Finish"
        }
    }
])

Test : MongoDB-Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM