根据条件在MongoDB聚合中添加具有递增值的字段 [英] Add a field with increasing value in MongoDB Aggregation based on condition

查看:37
本文介绍了根据条件在MongoDB聚合中添加具有递增值的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的收藏样本:

[
  {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    age: 55,
    location: "texas",
    joining_date: 2019-01-01T15:24:15.068+00:00
  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    location: "texas",
    joining_date: 2019-01-01T15:24:15.068+00:00
  },
  {
    _id: "bmasndvhjbca",
    name: "stuart",
    occupation: "lab assistant",
    age: 25,
    location: "texas",
    joining_date: 2019-01-02T20:25:16.068+00:00
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas"
  }
]

文档中有 joining_date 列的人需要通过检查诸如 joining_date_count:1

Which ever docs has joining_date column need to add a field with increasing value by checking the date like joining_date_count:1

如果日期相同,例如两种情况下的 mark lucas .计数应将其视为不同的值,并增加计数.

if the dates are same like in two cases mark and lucas . count should consider it as different values and increase the count.

预期输出:

[
  {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    age: 55,
    location: "texas",
    joining_date: 2019-01-01T15:24:15.068+00:00,
    joining_date_count:1
  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    location: "texas",
    joining_date: 2019-01-01T15:24:15.068+00:00,
    joining_date_count:2
  },
  {
    _id: "bmasndvhjbca",
    name: "stuart",
    occupation: "lab assistant",
    age: 25,
    location: "texas",
    joining_date: 2019-01-02T20:25:16.068+00:00,
    joining_date_count:3
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas"
  }
]

推荐答案

此聚合添加了一个带有计数器的字段:

This aggregation adds a field with a counter:

db.collection.aggregate( [
  { 
      $match: { 
          joining_date: { $exists: true } 
      } 
  },
  { 
      $group: { 
          _id: null, 
          docs: { $push: "$$ROOT" } 
      } 
  },
  { 
      $project: { 
          _id: 0,
         R: { 
             $map: {
                 input: { $range: [ 0, { $size: "$docs" } ] },
                 in: {
                     $mergeObjects: [ 
                         { joining_date_count: { $add: [ "$$this", 1 ] } },
                         { $arrayElemAt: [ "$docs", "$$this" ] }
                     ]
                 }
             }
         }
      }
  },
  { 
      $unwind: "$R" 
  },
  { 
      $replaceRoot: { newRoot: "$R" } 
  }
] )

这篇关于根据条件在MongoDB聚合中添加具有递增值的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆