【问题标题】:MongoDB get user which are new todayMongoDB获取今天的新用户
【发布时间】:2020-05-01 05:52:12
【问题描述】:

我正在尝试查找第 1 天的新用户列表。我写了查询来查找前天到达的用户和昨天到达的用户列表。现在我想减去这些数据,如何在单个聚合函数中做到这一点。

获取昨天之前的列表的功能

  db.chat_question_logs.aggregate([
    {  
        $match : {"createdDate":{$lte: ISODate("2020-04-29T00:00:00Z")}}
    },
    {
        "$project" :
        {
           _id : 0,
            "userInfo.userId":1
        }
    },
    { 
        "$group": {
        "_id": {userId:"$userInfo.userId"},"count": {$sum : 1}}

    } 
])

第 1 天类似如下

db.chat_question_logs.aggregate([
    {  
        $match : {"createdDate":{$gte: ISODate("2020-04-30T00:00:00Z"),$lte: ISODate("2020-05-01T00:00:00Z")}}
    },
    {
        "$project" :
        {
           _id : 0,
            "userInfo.userId":1
        }
    },
    { 
        "$group": {
        "_id": {userId:"$userInfo.userId"},"count": {$sum : 1}}

    } 
])

结果 JSON 如下

/* 1 */
{
    "_id" : {
        "userId" : "2350202241750776"
    },
    "count" : 1
},

/* 2 */
{
    "_id" : {
        "userId" : "26291570771793121"
    },
    "count" : 1
},

/* 3 */
{
    "_id" : {
        "userId" : "2742872209107866"
    },
    "count" : 5
},

/* 4 */
{
    "_id" : {
        "userId" : "23502022417507761212"
    },
    "count" : 1
},

/* 5 */
{
    "_id" : {
        "userId" : "2629157077179312"
    },
    "count" : 43
}

我怎样才能找到不同之处。

【问题讨论】:

  • 现在我要减去那些数据是什么意思?
  • 我想要今天或任何一天的新用户列表。新意味着他们在那一天之前不在日志中。
  • 我认为两个查询结果之间没有交叉或重复的文档,第一个是针对29/04/2020或之前创建的文档,第二个是针对在 2020 年 4 月 30 日至 2020 年 1 月 5 日之间创建的文档,“减去他们”是什么意思?

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

听起来你想要的是让所有用户在昨天创建(在本例中是 28 日)。

 db.chat_question_logs.aggregate([
{  
    $match : { $and: [ 
        { "createdDate":{$lt: ISODate("2020-04-29T00:00:00Z")} },
        { "createdDate": {$gte: ISODate("2020-04-28T00:00:00Z") }}
    ] }
},
{
    "$project" :
    {
       _id : 0,
        "userInfo.userId":1
    }
},
{ 
    "$group": {
    "_id": {userId:"$userInfo.userId"},"count": {$sum : 1}}

} 

])

这是你想要的吗?

【讨论】:

    【解决方案2】:

    您好,找到了下面的解决方案
    我使用了 Id 的组和首次出现,然后在我想要的日期过滤记录。
    查询如下

    db.chat_question_logs.aggregate([
    {
        $group:
         {
           _id: "$userInfo.userId",
           firstApprance: { $first: "$createdDate" }
         }   
    },
    {   
        $match : { "firstApprance": { $gte: new ISODate("2020-05-03"), $lt: new ISODate("2020-05-05") } }   
    }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多