[英]Write mongodb query using Count , DISTINCT & SUM for the following scenario
的mysql:
SELECT COUNT(DISTINCT col1, col2) AS 'aggCol1',
SUM(col3 = "2016-03-04 00:00:00" AND col5 = 29) AS 'aggCol2'
FROM table1
WHERE col4 = 50;
我想在MongoDB上寫查詢。
您可以使用Aggregation Framework:
要按col4
過濾,您應該使用$ match
要將您的集合轉換為單個結果,您需要將_id
設置為null
$ group
要獲得col1
和col2
不同值,可以使用$ addToSet
要對col3
和col5
使用嵌套過濾,您需要$ filter
要獲取數組長度,可以使用$ size
因此,整個聚合應如下所示:
db.col.aggregate([
{
$match: { col4: 50 }
},
{
$group: {
_id: null,
c12: { $addToSet: { col1: "$col1", col2: "$col2" } },
c3: { $push: { col3: "$col3", col5: "$col5" } }
}
},
{
$project: {
c12: 1,
c3: {
$filter: {
input: "$c3",
as: "item",
cond: { $and: [
{ $eq: [ "$$item.col3", ISODate("2016-03-04") ] },
{ $eq: [ "$$item.col5", 29 ] }
] }
}
}
}
},
{
$project: {
aggCol1: { $size: "$c12" },
aggCol2: { $size: "$c3" }
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.