使用 mongodb 聚合管道按升序向集合中的所有记录添加日期

Posted

技术标签:

【中文标题】使用 mongodb 聚合管道按升序向集合中的所有记录添加日期【英文标题】:Add date to all records in a collection in ascending order using mongodb aggregation pipeline 【发布时间】:2020-07-20 13:50:03 【问题描述】:

是否可以在聚合中为特定日期的所有记录添加日期

[
 
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas",


  ,
  
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:true,
    location: "texas",

  ,
  
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas",

  
]

有没有办法从这个日期date:2019-11-25T01:00:00.000+00:00 以这样的升序添加所有记录的日期

[
 
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas",
    date:2019-11-25T01:00:00.000+00:00


  ,
  
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:true,
    location: "texas",
    date:2019-11-26T01:00:00.000+00:00

  ,
  
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas",
    date:2019-11-27T01:00:00.000+00:00

  
]

mongodb 4.0版

【问题讨论】:

【参考方案1】:

您可以通过以下查询实现此目的:

db.collection.aggregate([
  
    $group: 
      _id: null,
      docs: 
        $push: "$$ROOT"
      
    
  ,
  
    $unwind: 
      path: "$docs",
      includeArrayIndex: "index"
    
  ,
  
    $addFields: 
      "docs.date": 
        $add: [
          
            $dateFromString: 
              dateString: "2019-11-25T01:00:00.000"
            
          ,
          
            $multiply: [
              "$index",
              
                $multiply: [
                  24,
                  60,
                  60,
                  1000
                ]
              
            ]
          
        ]
      
    
  ,
  
    $replaceRoot: 
      newRoot: "$docs"
    
  
])

测试一下here

【讨论】:

【参考方案2】:

这个聚合得到了预期的结果:

THIS_DATE = ISODate("2019-11-25T01:00:00.000+00:00")

db.collection.aggregate( [
   
      $group:  
          _id: null, 
          docs:  $push: "$$ROOT"  
       
  ,
   
      $project:  
         _id: 0,
         docs:  
             $map: 
                 input:  $range: [ 0,  $size: "$docs"  ] ,
                 in: 
                     $mergeObjects: [ 
                          date:  $add: [ THIS_DATE,  $multiply: [ "$$this", 24*60*60*1000 ]  ]  ,
                          $arrayElemAt: [ "$docs", "$$this" ] 
                     ]
                 
             
         
      
  ,
   
      $unwind: "$docs" 
  ,
   
      $replaceRoot:  newRoot: "$docs"  
  
] )

【讨论】:

以上是关于使用 mongodb 聚合管道按升序向集合中的所有记录添加日期的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 MongoDB 聚合管道从集合中的两个子文档中返回最小值?

MongoDB基础教程系列--第七篇 MongoDB 聚合管道

mongoDB表与表的关系及聚合管道查询

mongdb的聚合管道

MongoDB——聚合管道之$group操作

MongoDB——聚合管道之$group操作