mongodb 基于动态字段名的Mongo集合查询

2ledvvac  于 2023-03-17  发布在  Go
关注(0)|答案(1)|浏览(199)

我在Mongo DB的记录是这样的

{
    "_id" : ObjectId("64100b43317d38bfe6238deb"),
    "email" : "email@google.com",
    "is_active" : true,
    "stage_id" : 2,
    "panel_members" : {
        "2" : [ 
            "33190069-4166-43f4-9d89-04c8ce13d459", 
            "43190069-4166-43f4-9d89-04c8ce13d458"
        ],
        "3" : [ 
            "53190069-4166-43f4-9d89-04c8ce13d459", 
            "63190069-4166-43f4-9d89-04c8ce13d458"
        ],
        "4" : [ 
            "73190069-4166-43f4-9d89-04c8ce13d459", 
            "83190069-4166-43f4-9d89-04c8ce13d458"
        ],
    }
}

我要执行如下查询

collection.find({"panel_members.<stage_id>":"43190069-4166-43f4-9d89-04c8ce13d458"})

其中阶段ID应从记录的stage_id键获取

此处stage_id为2这意味着它应触发如下查询

collection.find({"panel_members.2":"43190069-4166-43f4-9d89-04c8ce13d458"})

我已经尝试了一些聚合查询,但它不工作.

f2uvfpb9

f2uvfpb91#

试试这个:

db.collection.aggregate([
   { $set: { panel_members: { $objectToArray: "$panel_members" } } },
   {
      $set: {
         panel_members: {
            $filter: {
               input: "$panel_members",
               cond: { $eq: ["$$this.k", { $toString: "$stage_id" }] }
            }
         }
      }
   },
   { $match: { $expr: { $in: ["43190069-4166-43f4-9d89-04c8ce13d458", { $first: "$panel_members.v" }] } } },
   { $set: { panel_members: { $arrayToObject: "$panel_members" } } }
])

Mongo Playground

相关问题