有一個過濾器myFilter用于獲取有關該xyz集合的一些見解。現在我需要運行三個具有相同步驟的查詢來過濾檔案
db.xyz.find(myFilter).sort(mySort1).limit(1) // get first item by sort #1
db.xyz.find(myFilter).sort(mySort2).limit(1) // get first item by sort #2
db.xyz.find(myFilter).count() // get total count
如何在單個查詢或聚合中表達相同的意圖?
預期結果是
{
"item_1": {/* first doc by (myFilter & mySort1) *//},
"item_1": {/* first doc by (myFilter & mySort2) *//},
"totalCount": /* count of all by myFilter */
}
uj5u.com熱心網友回復:
您可以使用$facet在一個查詢中對同一資料運行多個管道:
db.collection.aggregate([
{$match: myFilter}
{$facet: {
item_1: [{sort1}],
item_2: [{sort2}],
totalCount: [{$group: {_id: null, count: {$sum:1}}}]
}}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/490020.html
上一篇:根據Javascript中陣列內物件陣列的條件進行過濾
下一篇:無法向mongodb進行身份驗證
