![](/img/trans.png)
[英]MongoDB aggregation query - return all items inside nested subdocument
[英]aggregation mongodb, return all subdocument after match
我有藏书,其中包含以下数据:
books: {
title: "Mickey",
subtitle: "The Mouse",
authors: [
{
name: "Walt Disney",
type: "Author"
},
{
name: "Donald Duffy",
type: "Co-Author"
},
categories: [
"kids, education"
]
]
}
我想做的是在$unwind
作者数组之后,然后将$match
与$regex
巧合,如果巧合的话,如果autor.name字段具有我要发送的任何字符串,例如
$match: { "author.name": {$regex: ".*walt.*", $options: "si"}, title: "Mickey"}
然后在$group
和$push
我的数组之后,我最终得到
books: {
title: "Mickey",
subtitle: "The Mouse",
authors: [
{
name: "Walt Disney",
type: "Author"
}, categories: [
"kids, education"
]
]
}
在mongodb中是否有一种方法或运算符可以在匹配字段后保留我的所有子文档,之所以要这样做,是因为在我的应用程序的前端,每个作者和类别都将链接到所有具有该名称或类别,我想显示所有这些。
您是说要在初始文档中包含“ Donald Duffy”? 如果是这样,您可以通过使用点符号来使用简单find
,因此您不必使用聚合。 db.collection.find({"authors.name": {$regex: ".*walt.*", $options: "si"}, "title": "Mickey"})
与聚合框架相同:
db.collection.aggregate([
{
$match: {
"authors.name": {$regex: ".*walt.*", $options: "si"},
"title": "Mickey"
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.