Mongo DB组记录并返回所选字段

时间:2016-06-01 10:42:20

标签: mongodb

我想根据特定值对文档进行分组。我还需要选择的键作为回报。

这是我的文件:

{
    title: "Add 1",
    userId: 1,
    description: "this is add 1",
    location: {
        city: "Newyork",
        address: "Street 1, Flat # 40"
        },
    createdAt: "2015-10-20",

    title: "Add 2",
    userId: 1,
    description: "this is add 2",
    location: {
        city: "Paris",
        address: "Street 2, Flat # 80"
        },
    createdAt: "2015-10-22",

    title: "Add 3",
    userId: 1,
    description: "this is add 3",
    location: {
        city: "Newyork",
        address: "Street 5, Flat # 58"
        },
    createdAt: "2015-10-23"
}

我想按location.city对文档进行分组。此外,我只需要标题和位置作为回报。

上述情况的查询应该是什么?

我试过这个问题:

Adds.aggregate([
                  { $match: { userId: params.userId } },
                  { $group: { _id: "$location.city" } },              
              ]);

以上查询只返回location.city,我想要完整的位置对象&标题。

2 个答案:

答案 0 :(得分:0)

假设您的数据实际上是这样的:

[
  {
    title: "Add 1",
    description: "this is add 1",
    location: {
        city: "Newyork",
        address: "Street 1, Flat # 40"
        },
    createdAt: "2015-10-20",
  },
  {
    title: "Add 2",
    description: "this is add 2",
    location: {
        city: "Paris",
        address: "Street 2, Flat # 80"
        },
    createdAt: "2015-10-22",
  },
  {
    title: "Add 3",
    description: "this is add 3",
    location: {
        city: "Newyork",
        address: "Street 5, Flat # 58"
        },
    createdAt: "2015-10-23"
  }
]

您可以使用聚合查询,例如:

db.adds.aggregate([
    { $group : 
        { 
            _id : "$location.city", 
            data : { $push : { "title" : "$title", "location" : "$location" } }
        }
    }
]);

答案 1 :(得分:0)

文档中缺少userId,如果您的集合看起来像这样,那么您的聚合函数是正确的。

{
    "title": "Add 1",
    "userId": 1,
    "description": "this is add 1",
    "location": {
        "city": "Newyork",
        "address": "Street 1, Flat # 40"
        },
    "createdAt": "2015-10-20"
},
{
    "title": "Add 2",
    "userId": 2 
    "description": "this is add 2",
    "location": {
        "city": "Paris",
        "address": "Street 2, Flat # 80"
        },
    "createdAt": "2015-10-22"
},
{
    "title": "Add 3",
    "userId": 1,
    "description": "this is add 3",
    "location": {
        "city": "Newyork",
        "address": "Street 5, Flat # 58"
        },
    "createdAt": "2015-10-23"
}

使用Mongodb的控制台进行测试

db.Adds.aggregate([ 
           { $match: { userId: 1 } }, 
           { $group: { _id: "$location.city" } } 
]);

为结果添加标题

db.Adds.aggregate([
    { $match: { userId: 1 } }, 
    {
        $group: {  
            _id: "$location.city", 
            title: {$push: "$title"}
        }
    }
]);