简体   繁体   中英

aggregation mongodb, return all subdocument after match

I have the collections books, with the following data:

books: {
  title: "Mickey",
  subtitle: "The Mouse",
  authors: [
    {
      name: "Walt Disney",
      type: "Author"
    },
    {
      name: "Donald Duffy",
      type: "Co-Author"
    },
    categories: [
      "kids, education"
    ]
  ]
}

What I am trying to do is after $unwind my authors array and then $match with $regex for coincidences if the field autor.name has whatever string I am sending, for example

$match: { "author.name": {$regex: ".*walt.*", $options: "si"}, title: "Mickey"}

then after $group and $push my array, I end up with

books: {
  title: "Mickey",
  subtitle: "The Mouse",
  authors: [
    {
      name: "Walt Disney",
      type: "Author"
    }, categories: [
      "kids, education"
    ]
  ]
}

Is there a way or operator in mongodb to keep all my subdocuments after a matching a field, the reason why I want this, is because on the front-end of my app every author and category would be a link to all the books that have that name or category and I want to display all of them.

You mean you want to include “Donald Duffy” as in your initial document? If so you can use simple find by making use of the dot notation so you won't have to use aggregation. db.collection.find({"authors.name": {$regex: ".*walt.*", $options: "si"}, "title": "Mickey"})

The same with aggregation framework:

db.collection.aggregate([
{
  $match: {
    "authors.name": {$regex: ".*walt.*", $options: "si"}, 
    "title": "Mickey"
  }
}
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM