假設我想從我的集合中獲取一個物件,一個到這個物件,我想添加一個屬性,該屬性將存盤一個物件陣列,其中包含與我的物件的一個??屬性匹配的 id 和標題(在我的案例系列中)。
示例我有這個物件作為我的初始查詢的結果
{
_id: 13123123123,
title: "TitleofObject",
series: "SeriesName",
}
然后我想查看同一個集合,其中我的物件的系列名稱相同(添加一個名為 sameSeries 的新屬性來存盤與系列匹配的物件)并且物件的最終結果應該如下所示
_id: 13123123123,
title: "TitleofObject",
series: "SeriesName",
sameSeries:
[
{
_id: 12312312,
title: "anothertitleofObject"
},
{
_id: 12312342312,
title: "anothertitleofObject2"
}
]
如何使用聚合方法實作這一點?
const book = await Book.aggregate([
{
$match: { _id: id }
},
])
uj5u.com熱心網友回復:
db.collection.aggregate([
{
"$group": { //Group by series
"_id": "$series",
"sameSeries": { //Create an object
$push: { //push the required fields
"title": "$title",
"_id": "$_id"
}
}
}
}
])
操場
db.collection.aggregate([
{
"$match": {
"_id": 13123123123,
"sameSeries": {
"$exists": false
}
}
},
{
"$lookup": {
"from": "collection",
"localField": "series",
"foreignField": "series",
"as": "sameSeries"
}
}
])
操場
要跳過父 id,你可以做一個切片
db.collection.aggregate([
{
"$match": {
"_id": 13123123123,
}
},
{
"$lookup": {
"from": "collection",
"localField": "series",
"foreignField": "series",
"as": "sameSeries"
}
},
{
"$project": {
_id: 1,
series: 1,
title: 1,
sameSeries: {
"$slice": [
"$sameSeries",
-1
]
}
}
}
])
玩
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/482843.html
