Monday, 17 April 2017

Retrieving only array objects with the selected conditions

I'm having quite a bit of trouble with aggregating only the specific array objects in my mongoDB express app. Here is the document structure:

[
  {
    name: "Object 3"
    components: [
      [
        { price: 121, timestamp: ISODate(...) },
        { price: 111, timestamp: ISODate(...) },
        ...
      ]
      [], [], [] // 4 components overall
    ]
  }
]

Now I basicly want to get all {price,timestamp} objects in an array where the price is, say, greater than 100 in a single component.
With just find() I have this, but as expected this just returns every Object which has a price field with greater than 100

// Searches every component[0] for objects with price > 100
db.collection(collection).find({
    'components.0.price': { $gte: 100 }
}).toArray(function (err, result) {
     if (err) throw err

     console.log(result)
})

Now I googled a bit and found some aggregation stuff with $filter, the problem is just my database is very big and my console actually times out because the process is out of memory. The thing is I have no idea if thats because I aggregate wrong or because of the big database. It didn't have problems with the above code which basically returns every Object (since every Object has so many requests everyone has one with > 100), so I suspect im using it wrong in the nested array:

db.collection(collection).aggregate([
    {
        $project: {
            'components.0': {
                $filter: {
                    input: '$components.0',
                    as: 'component',
                    cond: { $gte: ['$$component.price', 200] }
                }
            }
        }
    }
]).toArray(function(err, result) {
    if (err) throw err

    console.log(result)
})



via nn3112337

No comments:

Post a Comment