仅检索具有所选条件的数组对象

时间:2017-04-17 21:34:17

标签: node.js mongodb express

我在mongoDB Express应用程序中仅聚合特定数组对象时遇到了一些麻烦。这是文档结构:

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

现在我基本上希望将所有{price,timestamp}对象放在一个数组中,例如,单个组件中的价格大于100。
只有find()我有这个,但正如预期的那样,它只返回每个具有大于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)
})

现在我用Google搜索了一下,发现了一些带有$ filter的聚合内容,问题只是我的数据库非常大而我的控制台实际上超时了,因为进程内存不足。事情是我不知道是不是因为我聚合错误或因为大数据库。它没有上述代码的问题,它基本上返回每个Object(因为每个Object都有这么多请求,每个人都有一个> 100),所以我怀疑我在嵌套数组中使用它错了:

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)
})

0 个答案:

没有答案