Mongodb seeks to return internal arrays

Asked

Viewed 232 times

2

Example of 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"
}

1 answer

1

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

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

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

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

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

  • only with {$unwind: "$products"}, already returns me separately even being in the same user, nice, but in $project would have to specify one by one, the problem is that adding another field would not be automatic...

  • As I commented in the reply, if you will only list products frequently, give a thought in your schema, maybe putting the products in a separate Collection.

Browser other questions tagged

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