使用其他字段值作为关键字查找MongoDB文档的字段值



示例文档:

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

我想搜索有多少文档的阶段状态是"完成",哪个阶段由"键"决定。

比如这个文档,关键字是"search",所以我想查询"phaseStatus.search"。如果另一个文档的关键字是"write",它会查询"phaseTtatus.write"。

我正在尝试使用$filter,但它的表达式必须是数组。我也试着喜欢它:

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

但没有奏效。如何查询动态字段?

您可以尝试以下查询:

查询:

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"
}
}
])

测试:MongoDB Playground

最新更新