如何筛选对象元素的数组mongoose?

时间:2017-02-17 12:17:19

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有以下架构:

User: {
  age: Number,
  name: String,
  comments: {
    added: Date,
    body: String
  }
}

我需要获取所有用户,评论的添加次数超过自定义日期。

示例数据:

[{
  "name": "John",
  "age: 21,
  "comments": [{
     "added": 21-01-12,
     "body": "blabla1"    
  }, {
     "added": 21-02-12,
     "body": "blabla2"    
  }, {
     "added": 21-01-10,
     "body": "blabla3"   
  }]
}, {
  "name": "Bruno",
  "age: 33,
  "comments": [{
     "added": 21-01-10,
     "body": "ololo1"    
  }, {
     "added": 21-02-12,
     "body": "ololo2"    
  }, {
     "added": 21-01-09,
     "body": "ololo3"   
  }]
}]

我需要所有评论都超过01-01-11而且评论不低于此日期的用户。

预期结果:

{
  "name": "John",
  "age: 21,
  "comments": [{
     "added": 21-01-12,
     "body": "blabla1"    
  }, {
     "added": 21-02-12,
     "body": "blabla2"    
  }]
}, {
  "name": "Bruno",
  "age: 33,
  "comments": [{
     "added": 21-02-12,
     "body": "ololo2"    
  }]
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

要过滤Mongoose(和mongo)中的日期字段,您需要使用$ gte,$ gt,$ lt,$ lte。在您的具体示例中,您需要$ gte(大于或等于)

因此,如果您的模型是用户 User.find({comments.added:{$ gte:new Date(2011,1,1)}},function(err,comments){

});

除非有某些原因,否则我可能会建议您更喜欢更准确的ISODate,并且您也会这样做以过滤条目

英里每小时

答案 1 :(得分:0)

const findQuery = [
    {$unwind: "$comments" },
    {$match: {"comments.added": {$gt: lastUpdate} } },
    {$group: {_id: "$_id", comments: {$push: "$comments"} } }
];

User.aggregate(findQuery)