Mongo find em array dentro de Collection

Asked

Viewed 1,223 times

3

Good people, this is my exit with the normal find:

{ 
    "_id" : ObjectId("57be6168ce98ad853a96282f"), 
    "nome" : "Mercado Padrão", 
    "userId" : "o4wQ2i4Dt7cAMNf9A", 
    "produtos" : [ 
         { 
             "nome" : "coca cola", 
             "vds" : [ 
                 { "desc" : "Sódio", "qtd" : "0,5", "vd" : "mg" } 
              ], 
              "est" : "100", "preco" : "5.50", "sku" : "KU177" 
         } 
     ] 
}

My question is how to make a query returning only the list of products of a specific userid.

for example: I want to view all userid products: o4wQ2i4Dt7cAMNf9A.

  • Without the "schema" of the bank gets a little complicated, but it is not the case of a simple find? db.tabela.find({userId:'o4wQ2i4Dt7cAMNf9A'}). I started in Mongo a little while ago but until where I know it will return you all the records with the userId == o4wQ2i4Dt7cAMNf9A

2 answers

0

This will return a list of the whole arrays to the user. If the user has more than one document in the collection, multiple arrays will return:

db.suacolecao.find({userId: "xxxxxxxxx"}, {produtos: 1})

If you need to combine all these possible arrays into a single array, you will need to use the Aggregation Framework. There is an example very similar to this problem here.

0

Use Aggregate and $match Amigo. To organize your filter, use $project:

db.XXXXX.aggregate([{
 $match: { userId: "o4wQ2i4Dt7cAMNf9A"} },{
 $project:{ userId: 1, produtos.nome: 1} }])

Browser other questions tagged

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