我有以下檔案
[
{
"_id": "624713340a3d2901f2f5a9c0",
"username": "fotis",
"exercises": [
{
"_id": "624713530a3d2901f2f5a9c3",
"description": "Sitting",
"duration": 60,
"date": "2022-03-24T00:00:00.000Z"
},
{
"_id": "6247136a0a3d2901f2f5a9c6",
"description": "Coding",
"duration": 999,
"date": "2022-03-31T00:00:00.000Z"
},
{
"_id": "624713a00a3d2901f2f5a9ca",
"description": "Sitting",
"duration": 999,
"date": "2022-03-30T00:00:00.000Z"
}
],
"__v": 3
}
]
我正在嘗試通過以下聚合獲取回傳的練習計數(我知道在我的代碼中這樣做更容易,但我試圖了解如何使用 mongodb 查詢)
db.collection.aggregate([
{
"$match": {
"_id": "624713340a3d2901f2f5a9c0"
}
},
{
"$project": {
"username": 1,
"exercises": {
"$slice": [
{
"$filter": {
"input": "$exercises",
"as": "exercise",
"cond": {
"$eq": [
"$$exercise.description",
"Sitting"
]
}
}
},
1
]
},
"count": {
"$size": "exercises"
}
}
}
])
當我嘗試使用 訪問該exercises欄位"$size": "exercises"時,出現錯誤query failed: (Location17124) Failed to optimize pipeline :: caused by :: The argument to $size must be an array, but was of type: string。
但是當我使用訪問子檔案時exercises,"$size": "$exercises"我得到了檔案中包含的所有子檔案的計數。
注意:我知道在此示例中我使用$slice并將限制設定為 1,但在我的代碼中它是一個變數。
uj5u.com熱心網友回復:
你實際上是在正確的軌道上。你真的不需要$slice. 您可以只使用$reduce來執行過濾。您的計數不起作用的原因是過濾和$size處于同一階段。在這種情況下,它將采用預先過濾的陣列來進行計數。您可以通過添加$addFields階段來解決此問題。
db.collection.aggregate([
{
"$match": {
"_id": "624713340a3d2901f2f5a9c0"
}
},
{
"$project": {
"username": 1,
"exercises": {
"$filter": {
"input": "$exercises",
"as": "exercise",
"cond": {
"$eq": [
"$$exercise.description",
"Sitting"
]
}
}
}
}
},
{
"$addFields": {
"count": {
$size: "$exercises"
}
}
}
])
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455196.html
上一篇:MongoDB宣告模型并洗掉資料
