Home > database >  Mongoose Query selecting parent and only matched children
Mongoose Query selecting parent and only matched children

Time:04-09

im having trouble query this type of data

[
{ev:1,
image:[{id:24,name:'ads1'},{id:25,name:'ads2'},{id:26,name:'ads4'},{id:27,name:'ads3'}]
 },
{ev:1,
image:[{id:29,name:'ads1'},{id:23,name:'ads2'},{id:34,name:'ads4'},{id:50,name:'ads3'}]
 }
 ]

this is my query

 var data =  schema.find( {

             $and: [
              {
               ev: 1
              },
              {
               'image.id': {
                $in: [26,29,50,34]
               }
              }
             ]
            
           } , 'ev image'  )

what result i need is

[
{ev:1,
image:[{id:26,name:'ads4'}]
 },
{ev:1,
image:[{id:29,name:'ads1'},{id:34,name:'ads4'}, {id:50,name:'ads3'}]
 }
 ]

Im using moongose

but i keep getting back the whole image array

i basically need the image object filtered with only the image.id i want

PS there are more ev 1,2,3.... hence i need to only find in the ev i provide

could someone please help me with this

im new to mongodb

CodePudding user response:

Find is used to keep or reject complete documents(find has a project also but in general for transformations we use aggregate operators). The bellow is aggregation that keeps only part of the array.

Query

  • match the ev=1
  • filter the image and keep only those that are contained in the the array [26, 29, 50, 34]
  • if you want you can add another match to filter out the documents with empty array (no id was member of the array)

PlayMongo

aggregate(
[{"$match": {"ev": {"$eq": 1}}},
 {"$set": 
   {"image": 
     {"$filter": 
       {"input": "$image",
        "cond": {"$in": ["$$this.id", [26, 29, 50, 34]]}}}}}])
  • Related