聚合mongodb,匹配后返回所有子文档

时间:2018-01-03 23:43:55

标签: javascript node.js mongodb aggregation

我有藏书,有以下数据:

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具有我发送的任何字符串,例如< / p>

$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中是否有一个方法或运算符可以在匹配字段后保留我的所有子文档,我之所以需要这个,是因为在我的应用程序的前端,每个作者和类别都将是一个链接到所有具有该名称或类别的书籍,我想显示所有这些书籍。

1 个答案:

答案 0 :(得分:0)

你的意思是你想在你的初始文件中加入“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"
  }
}
])
相关问题