Home > Back-end >  Mongoose : Filter an nested array for each document
Mongoose : Filter an nested array for each document

Time:11-28

// Schema:
const UserSchema = mongoose.Schema({
  name: { type: String },
  motos: [
    {
     model: { type: String }
    },
  ],
});

// Motos enabled:
  motosEnabled = [
    {
      model: 'A1',
    },
    {
      model: 'A2',
    },
  ];

User.insertMany([
  { name: 'Kartik', motos: [{ model: 'A1' }, { model: 'A3' }] },
  { name: 'Niharika', motos: [{ model: 'A1' }, { model: 'A2' }] },
])

I want to write a query which will return all users but filter only the motos enabled of the previous array. I'am trying to use aggregation but I can't do it. Thanks for any help !

Output expected :

[
  { name: 'Kartik', motos: [{ model: 'A1' }] },
  { name: 'Niharika', motos: [{ model: 'A1' }, { model: 'A2' }] }
]

CodePudding user response:

Query

  • you can use $filter
  • instead of [{"model": "A1"}, {"model": "A2"}] put the js variable motosEnabled
  • filter checks if the array(motosEnabled) contains the document {"model" ".."} and it passes or not

Test code here

aggregate(
[{"$set": 
   {"motos": 
     {"$filter": 
       {"input": "$motos",
        "cond": 
         {"$in": 
           [{"model": "$$this.model"}, [{"model": "A1"}, {"model": "A2"}]]}}}}}])
  • Related