mongoDb按字段查找文档中的条目数和不同的条目

时间:2015-07-21 08:21:14

标签: mongodb mongoose mongoid mongodb-query

我的文档结构是:

[{
    "l": {
    "ln": "Hyderabad",

    },
    "cid": "customer1",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Hyderabad",

    },
    "cid": "customer2",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Delhi",

    },
    "cid": "customer3",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Delhi",

    },
    "cid": "customer3",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer1",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer5",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer6",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}, {
    "l": {
    "ln": "Bangalore",

    },
    "cid": "customer6",
    "created": ISODate("2015-07-20T13:15:45.198        Z")
}]

我的o / p应该是:

[{
    "ln": "Hyderabad",
    "entries": 2,
    "numberofdistinctcustomers": 2,
    "customers": [
    "customer1",
    "customer2"
    ]
} {
    "ln": "Delhi",
    "entries": 2,
    "numberofdistinctcustomers": 1,
    "customers": [
    "customer3"
    ]
} {
    "ln": "Bangalore",
    "entries": 4,
    "numberofdistinctcustomers": 3,
    "customers": [
    "customer1",
    "customer5",
    "customer6"
    ]
}]

有人可以帮我这个吗?我理解为此我们需要使用ln $group来查找entries。如何查找不同cids的数量?

请帮帮我吗?

1 个答案:

答案 0 :(得分:1)

您应该使用aggregation来获得预期的输出。

首先,您需要按l.ln分组,然后使用customers获得不同的$addToSet。要获得numberofdistinctcustomers,您可以在投影中使用$size运算符。

查询如下:

db.collection.aggregate({
    $group: {
    _id: "$l.ln",
    "entries": {
        $sum: 1
    },
    "dis": {
        $addToSet: "$cid"
    }
    }
}, {
    $project: {
    "ln": "$_id",
    "entries": 1,
    "customers": "$dis",
    "numberofdistinctcustomers": {
        "$size": "$dis"
    }
    }
})