Mongodb seeks to return internal arrays

2

Example structure:

{
  "_id" : ObjectId("598d4eb912f28534d80a5820"),
  "nome" : "Emilio",
  "produtos" : [
   {
     "_id" : ObjectId("598d4fb912f28534d80a5821"),
     "nome" : "produto1"
   },
   {
     "_id" : ObjectId("598d4fb912f28534d80a5822"),
     "nome" : "produto2"
   }
  ]
},
{
  "_id" : ObjectId("598d4eb912f28534d80a5821"),
  "nome" : "Zezinho",
  "produtos" : [
   {
     "_id" : ObjectId("598d4fb912f28534d80a5825"),
     "nome" : "produto3"
   }
  ]
}

How do I search only the "products" of all users and return something like this:

{
  "_id" : ObjectId("598d4fb912f28534d80a5821"),
  "nome" : "produto1"
},
{
  "_id" : ObjectId("598d4fb912f28534d80a5822"),
  "nome" : "produto2"
},
{
  "_id" : ObjectId("598d4fb912f28534d80a5825"),
  "nome" : "produto3"
}
    
asked by anonymous 11.08.2017 / 09:25

1 answer

0

To do this you need to use an aggregation (I used teste as the name of the collection):

db.teste.aggregate(
    {$unwind: "$produtos"},   
    {$project: {"_id" : "$produtos._id", "nome": "$produtos.nome"}}
)

The $ unwind operator deconstructs an array field, returning a separate document for each element .

With $ project you can tell which fields will be shown on output.

If you are going to list all products frequently, I suggest rethinking your schema, it would be best to store the products in a separate collection. Always consider how you will access / modify the data to define the structure.

    
11.08.2017 / 14:08