聚合 mongodb, return 匹配后的所有子文档
aggregation mongodb, return all subdocument after match
我有 collections 本书,数据如下:
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 中有没有一种方法或运算符可以在匹配字段后保留我的所有子文档,我想要这个的原因是因为在我的应用程序的 front-end 上,每个作者和category 将是所有具有该名称或类别的书籍的 link,我想显示所有这些书籍。
你的意思是你想在你的初始文档中包含“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"
}
}
])
我有 collections 本书,数据如下:
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 中有没有一种方法或运算符可以在匹配字段后保留我的所有子文档,我想要这个的原因是因为在我的应用程序的 front-end 上,每个作者和category 将是所有具有该名称或类别的书籍的 link,我想显示所有这些书籍。
你的意思是你想在你的初始文档中包含“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"
}
}
])