我有一個這樣的集合:
{
_id: "blabla",
userName: "blablabla",
..
interactedUsers: [
"blabla2"
"some other user's id",
"some other user's id",
]
},
{
_id: "blabla2",
userName: "blablabla2",
..
interactedUsers: [
"some other user's id",
"some other user's id",
]
},
現在,如果我是"_id: "blabla"我想要獲取所有用戶的用戶,除了"blabla2"因為它在我的"interactedUsers"陣列中。我怎樣才能做到這一點?我嘗試了很多聚合組合,但無法真正得到想要的結果。
uj5u.com熱心網友回復:
由于您可能不想使用$facet它,因為它將所有集合合并到一個大檔案中,另一種選擇是使用$lookup.
這允許您將“忽略”的檔案添加到所有其他檔案中,然后從答案中洗掉包含它的檔案。這樣做的好處是您的所有檔案在整個程序中都是分開的:
db.collection.aggregate([
{
$addFields: {"ignore": "blabla" }
},
{
$lookup: {
from: "collection",
localField: "ignore",
foreignField: "_id",
as: "ignore"
}
},
{
$set: {ignore: {$arrayElemAt: ["$ignore", 0]}}
},
{
$match: {
$expr: {$not: {$in: ["$_id", "$ignore.interactedUsers"]}}
}
},
{
$unset: "ignore"
},
{
$match: {$expr: {$ne: ["$_id", "blabla"]}}
}
])
游樂場示例
uj5u.com熱心網友回復:
這是另一種回傳"_id"集合中的所有內容而不是"interactedUsers".
db.collection.aggregate([
{ "$match": { "_id": "blabla0" } },
{
"$lookup": {
"from": "collection",
"let": { "notIds": { "$setUnion": [ [ "$_id" ], "$interactedUsers" ] } },
"pipeline": [
{ "$match": { "$expr": { "$not": { "$in": [ "$_id", "$$notIds" ] } } } },
{ "$project": { "_id": 1 } }
],
"as": "strangers"
}
},
{
"$set": {
"strangers": {
"$map": {
"input": "$strangers",
"in": "$$this._id"
}
}
}
}
])
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/477723.html
