私はコレクションを持っていますUsers
:
{
_id: "5cds8f8rfdshfd"
name: "Ted"
attending: [ObjectId("2cd9fjdkfsld")]
}
私は別のコレクションを持っていますEvents
:
{
_id: "2cd9fjdkfsld"
title: "Some Event Attended"
},
{
_id: "34dshfj29jg"
title: "Some Event NOT Attended"
}
特定のユーザーが参加しているすべてのイベントのリストを返したいのですが。ただし、Events
これはより大きなクエリの一部であるため、コレクションからこのクエリを実行する必要があります。
私は次の質問をしました:
私は自分の状況に合うように上記の答えを修正するさまざまな方法を試しましたが、失敗しました。3番目の質問の2番目の回答は私に最も近いものですが、値0で返されるのではなく、一致しない結果を除外したいと思います。
私の希望する出力:
[
{
_id: "2cd9fjdkfsld"
title: "Some Event Attended"
},
]
1つのオプションは次のようになります。
db.getCollection('Events').aggregate({
$lookup: // join
{
from: "Users", // on Users collection
let: { eId: "$_id" }, // keep a local variable "eId" that points to the currently looked at event's "_id"
pipeline: [{
$match: { // filter where
"_id": ObjectId("5c6efc937ef75175b2b8e7a4"), // a specific user
$expr: { $in: [ "$$eId", "$attending" ] } // attends the event we're looking at
}
}],
as: "users" // push all matched users into the "users" array
}
}, {
$match: { // remove events that the user does not attend
"users": { $ne: [] }
}
})
users
必要に応じて別の投影を追加することで、明らかにフィールドを取り除くことができます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加