我正在嘗試查詢集合中包含特定用戶資料的所有檔案而不回傳所有子檔案(有大量子檔案)
示例檔案
[
{
"id": 1,
"title": "Document 1",
"users": [
{ "id": "a", "name": "User 1" },
{ "id": "b", "name": "User 1" },
]
},
{
"id": 2,
"title": "Document 2",
"users": [
{ "id": "b", "name": "User 1" },
]
},
{
"id": 3,
"title": "Document 3",
"users": [
{ "id": "a", "name": "User 1" },
{ "id": "b", "name": "User 1" },
{ "id": "c", "name": "User 1" },
]
}
]
這里我們有 3 個檔案,其中 2 個使用了 id A,查詢我正在執行的用戶 A 存在的所有檔案:
collection.findManyByQuery({
users: {
$elemMatch: {
id: 'a'
}
}
})
這會回傳正確的 id 為 1 和 3 的檔案。但是我試圖回傳只有用戶陣列內的用戶 A 物件的檔案,所以我的結果看起來像這樣
[
{
"id": 1,
"title": "Document 1",
"users": [
{ "id": "a", "name": "User 1" },
]
},
{
"id": 3,
"title": "Document 3",
"users": [
{ "id": "a", "name": "User 1" },
]
}
]
我已經嘗試$unwind: 'users'了幾個過濾器,但沒有得到想要的結果。
uj5u.com熱心網友回復:
使用投影臺。
根據檔案:
投影引數確定匹配檔案中回傳哪些欄位
因此,使用users.$: 1您告訴 mongo:“從符合條件的用戶回傳值”。在這種情況下,標準是id: "a"。
db.collection.find({
users: {
$elemMatch: {
id: "a"
}
}
},
{
"users.$": 1
})
這里的例子
您也可以像本例中那樣使用users.id查找查詢
也許是一個更干凈的查詢,只有兩行:
db.collection.find({
"users.id": "a"
},
{
"users.$": 1
})
編輯:
要向輸出添加更多值(如title或id),您必須添加到投影階段。默認情況下,投影只回傳_id和 帶有1or的值true。
檢查這個例子
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427366.html
上一篇:Mongoose,聚合與Js函式
