假設我有一個這樣的檔案:
{
_id: ObjectId("1234567890"),
author: "ABC1",
text:"this is a Post",
details: {
time: "14/05/2015",
Edit: "none"
},
comments: [
{
comment_text: "Hello",
user: "alan",
time:"20/05/2014 20:44"
},
{
comment_text: "Hi Every One",
user: "bob",
time:"20/05/2014 20:44"
},
{
comment_text: "Good morning , Alan",
user: "Alan",
time:"20/05/2014 20:44"
},
{
comment_text: "I'm bob",
user: "bob",
time:"20/05/2014 20:44"
},
],
category: "IT"
}
我想構建一個回傳此物件的查詢,但在 comments 陣列中只有 Bob 的評論。
{
author: "ABC1",
text:"this is a Post",
details: {
time: "14/05/2015",
Edit: "none"
},
comments: [
{
comment_text: "Hi Every One",
user: "bob",
time:"20/05/2014 20:44"
},
{
comment_text: "I'm bob",
user: "bob",
time:"20/05/2014 20:44"
},
],
category: "IT"
}
如何才能做到這一點?
- 在聚合管道中使用
$unwind(and$match) 將獲得正確的子檔案,但不會作為原始檔案中的物件陣列。 $elemMatch在投影中使用(使用find()或findOne())僅回傳第一個匹配的注釋(子檔案)。
uj5u.com熱心網友回復:
您可以$filter在$project聚合管道的階段使用運算子:
db.collection.aggregate([
{
$project: {
_id: 0,
author: 1,
text: 1,
details: 1,
category: 1,
comments: {
$filter: {
input: "$comments",
as: "comment",
cond: {
$eq: [
"$$comment.user",
"bob"
]
}
}
}
}
}
])
示例 mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339367.html
