Mongodb query and return array specific elements within objects

Asked

Viewed 2,484 times

1

Guys, I need a help to query certain values in a document.

I have a collection in Mongo that follows this structure, including this is the document I can and need to locate: https://github.com/pedrualves/document/blob/master/school.js

find this quiet I find document without problems using the criterio: "pages": 32

The problem I have is to display only the array items that are in objects, as follows, is what I hope to return from the query by "pages": 32 :

{
"book": [
 {
  "pages": 32,
  "title": "a"
 },
 {
  "pages": 32,
  "title": "c"
 },
 {
  "pages": 32,
  "title": "d"
 }
]
}

will anyone can give me the path of stones, tips or suggestions???

1 answer

1


You can use the Aggregate Unwind to break the array so Voce can group and filter.

db.'collection_name'.aggregate([
{ $unwind : "$students" },
{ $unwind : "$students.class" },
{ $unwind : "$students.class.book" },
{$match:{"students.class.book.pages":{$in:[32]}}},
{$group:
{
_id:'$students.name',
teste:{$push:'$students.class.book'}
}
}
])

Can also be used $redact

Browser other questions tagged

You are not signed in. Login or sign up in order to post.