2016-06-23 53 views
0

如何获取大于特定日期的子文档的计数。 假设我有以下模型,我希望获得大于特定日期的聊天计数。Mongodb获得特定字段的计数

model = { 
"chats" : [ 
    { 
     "comment" : "hi", 
     "_id" : ObjectId("576a2107aa7940f029ce6547"), 
     "createdDateTime" : ISODate("2016-06-22T05:24:23.422Z") 
    }, 
    { 
     "comment" : "asdasdsa", 
     "_id" : ObjectId("576a2367aa7940f029ce6548"), 
     "createdDateTime" : ISODate("2016-06-22T05:34:31.628Z") 
    }, 
    { 
     "comment" : "dsadasd", 
     "_id" : ObjectId("576a2369aa7940f029ce6549"), 
     "createdDateTime" : ISODate("2016-06-22T05:34:33.354Z") 
    }, 
],} 

我已经与

   Model.count({ 
       $and: [ 
        { 'chats.createdDateTime': {$lt: '2016-06-22T10:03:21.879Z' } }, { '_id':messages[index]._id } 
       ] 
      }) 

尝试也试过一些其他类似的方法。 任何人都可以帮助我吗?

如果可能的话请建议使用聚合框架。

+0

我不认为有可能没有聚合。 – Shrabanee

+0

好吧,但在这里我列出了数据,并且需要在特定日期之后统计每个列表聊天。你能建议一种方法吗? –

+0

您正在使用的mongodb的版本是什么? – Shrabanee

回答

0

尝试使用Data而不是String

Model.count({ 
      $and: [ 
       { 'chats.createdDateTime': {$lt: new Date() } }, 
       { '_id':messages[index]._id } 
      ] 
     }) 
+0

什么是'new Data()'? – Shrabanee

+0

对不起,我打错了,我的意思是'新日期()'。 –

+0

这不会帮助解决我认为问题中提到的问题。它将投影“聊天”数组的所有对象,而不是仅投影符合条件的对象。 – Shrabanee

0

如果您是怎么运用aggreagte,下面的查询可以帮助你: -

var date = '2016-06-22T10:03:21.879Z', 

db.collection.aggregate([ 
{ 
    "$match": { 
     "chats.createdDateTime": { "$gt": date} 
    } 
}, 
{ 
    "$project": { 
     "chats": { 
      "$filter": { 
       "input": "$chats", 
       "as": "o", 
       "cond": { 
        "$gt": [ "$$o.createdDateTime", date ] },    
        ] 
       } 
      } 
     } 
    } 
}]) 

通过使用查询,chats将只包含与提供的条件相匹配的对象。

现在,您可以从每个文档中获取chats数组的长度,这将为您提供所需的计数。

希望这会有所帮助!

相关问题