MongoDB查询过滤器对象数组和格式返回对象

时间:2019-01-30 08:34:54

标签: json mongodb mongodb-query

我有一个这样的MongoDB集合:

{
    "_id" : "course1",
    "teams" : [ 
        {
            "key" : "1548600639880X5269760768997986",
            "title": "Team One",
            "members" : {
                "user1" : true
            }
        }, 
        {
            "key" : "1548601941683X14679065888073906",
            "title": "Team Two",
            "members" : {
                "user2" : true,
                "user3" : true
            }
        }, 
        {
            "key" : "1548602385020X41594057288000386",
            "title": "Team Three",
            "members" : {
                "user4" : true
            }
        }
    ],
    "updated_at" : "2019-01-27T15:31:43+00:00"
}

我正在尝试让所有值为true的用户与user2组成团队。所以返回对象应该是这样的:

 {
     "key" : "1548601941683X14679065888073906",
     "title": "Team Two",
     "members" : {
         "user2" : true,
         "user3" : true
     }
  }

我用db.getCollection('')。find({})尝试了很多,但没有得到所需的结果。

2 个答案:

答案 0 :(得分:0)

db.getCollection('teams').find({
    "_id": "course1",
    "teams.members": { "user1": true }
})

得到我

{
    "_id" : "course1",
    "teams" : [ 
        {
            "key" : "1548600639880X5269760768997986",
            "title" : "Team One",
            "members" : {
                "user1" : true
            }
        }, 
        {
            "key" : "1548601941683X14679065888073906",
            "title" : "Team Two",
            "members" : {
                "user2" : true,
                "user3" : true
            }
        }, 
        {
            "key" : "1548602385020X41594057288000386",
            "title" : "Team Three",
            "members" : {
                "user4" : true
            }
        }
    ],
    "updated_at" : "2019-01-27T15:31:43+00:00"
}

答案 1 :(得分:0)

您需要使用aggregation。在聚合下面可以帮助您。

db.getCollection('')。find({})不能将输出转换为所需结果。

db.getCollection('collection').aggregate([
    { $unwind: "$teams" },
    { $match: {"teams.members.user2": true } },
    { $replaceRoot: { newRoot: "$teams" }  } 
])