我是 mongoDB 的新手,因此在根據需要過濾我的集合時遇到了一些困難。
我有這個收藏
[
{
"id": "sdfsdfsdf",
"key": "tryrtyrty",
"createdAt": "2017-01-28T01:22:14.398Z",
"counts": [
170
],
"value": "Something"
},
{
"id": "hjmhjhjm",
"key": "yuiyuiyui",
"createdAt": "2017-01-28T01:22:14.398Z",
"counts": [
150,
160
],
"value": "Something"
}
]
我想按日期范圍(最小-最大日期)和計數范圍進行過濾,這意味著我想為field. 例如,我想過濾最小計數總和為 200 且最大計數為 400 的結果。這只會回傳第二個結果(總和為 310,而第一個結果總和為 170)。
現在我有這個:
db.collection.aggregate([
{
$project: {
totalCount: {
$sum: {
"$filter": {
"input": "$counts",
"as": "bla",
"cond": {
"$gte": [
"$sum", // I think the error is here, I dont know how to reference the sum of the list
300 //I want records whose count sum is more than this value
]
}
}
}
}
}
}
])
這將回傳所有帶有TotalCounton的記錄0,這不是我想要的,我希望記錄與正確的 TotalCount 匹配計數條件(并最終匹配日期)
[
{
"_id": ObjectId("5a934e000102030405000000"),
"totalCount": 0
},
{
"_id": ObjectId("5a934e000102030405000001"),
"totalCount": 0
}
期望的輸出
[
{
"_id": ObjectId("5a934e000102030405000001"),
"totalCount": 310,
"key": "yuiyuiyui",
"createdAt": "2017-01-28T01:22:14.398Z"
}
]
任何幫助將不勝感激。如果它帶有日期和計數過濾器,則更是如此。
uj5u.com熱心網友回復:
您不應該使用$filter它,因為它不適合這種情況。
階段:
set-totalCounts使用陣列中的$sum所有元素創建。counts$match- 適合范圍內的檔案totalCounts。$unset- 洗掉用于裝飾輸出檔案的欄位。
db.collection.aggregate([
{
$set: {
"totalCounts": {
$sum: "$counts"
}
}
},
{
$match: {
totalCounts: {
$gte: 200,
$lte: 400
}
}
},
{
$unset: [
"counts",
"id"
]
}
])
示例 Mongo Playground
對于日期范圍過濾器,您需要$expr和$and運算子如下
{
$match: {
totalCounts: {
$gte: 200,
$lte: 400
},
$expr: {
$and: [
{
$gte: [
{
"$toDate": "$createdAt"
},
/* Date from */
]
},
{
$lte: [
{
"$toDate": "$createdAt"
},
/* Date to */
]
}
]
}
}
}
示例 Mongo Playground(帶有日期范圍過濾器)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429514.html
