MongoDB:搜索对象

时间:2018-06-22 14:53:41

标签: mongodb mongodb-query aggregation-framework

我收藏了下一件商品(例如一件商品)

{
    "_id": ObjectId("5b2cb384ee93081e2b2b1ffd"),
    "publishedItems": {
        "0a4ec2faf5b08ece993a7949739b9727": {"id":"1234"},
        "0a4ec2faf5b08ece993a79497391234": {"id":4567},
        "12332faf5b08ece993a7949739b9727": {"id":"7890"},
},
    "currentContentKey": "0a4ec2faf5b08ece993a7949739b9727",
    "draft": {}
}

我想通过publishedItems中的id获取此项目 我使用下一个查询

db.getCollection('items').aggregate([
{
   $project:{
       "_id":1,
       currentContentKey:1,
       published:"$publishedItems"
   }
},
{
   $match:{
       $or:[
           {
               "published.currentContentKey.id":"1234"
           }
       ]
   }
}
])

是否可以在点表示法查询中的$ project中使用 currentContentKey ?是否可以创建一个查询以从PublishedItems通过ID获取项目?

更新

感谢@AlexBlex

我的最终查询是:

db.getCollection('items').aggregate([
{
   $project:{
       "_id":1,
       currentContentKey:1,
       published: "$publishedItems",
       pub:{$objectToArray:"$publishedItems"}
   }
},
{
   $match:{
       $or:[
           {
               "pub":{$elemMatch:{"v.id": ObjectId("5b2cb3ca367df10631f1aac7")}}
           }
       ]
   }
}
])

1 个答案:

答案 0 :(得分:1)

您可以结合使用$objectToArray$filter

db.getCollection('items').aggregate([
    { $addFields: {
        currentPublished: { $arrayElemAt: [
            { $filter: { 
                input: { $objectToArray: "$publishedItems" }, 
                as: "one", 
                cond: { $eq: ["$$one.k", "$currentContentKey"]} 
            } },
            0
         ] }
    } },
    { $match: {
        $or:[
            {"currentPublished.v.id": "1234"}
        ]
    } }
    { $project: {
        "_id":1,
        currentContentKey:1,
        published:"$publishedItems"
    } },
])