如何使用MongoDB的聚合框架替换空日期字段?

时间:2013-10-15 20:11:32

标签: ruby mongodb mongoid aggregation-framework mongoid3

使用 Rails 3.2.14,Ruby 1.9.3,Mongoid 3.1.5

我正在查询看起来像这样的文件:

{
   paid_on: ISODate("2013-03-08T22:25:24.973Z"),
   paid_amt: 25.5
}

有时 paid_on null,但我也需要捕获这些文档,因此我尝试使用 $ ifNull 替换默认日期:

Claim.collection.aggregate(
    {
        "$project" => {
            "paid_on"  => {"$ifNull" => ["$paid_on", Date.new(1980, 1, 1).mongoize]},
            "paid_amt" => 1,
        }
    }
)

发送给Mongo的查询看起来像这样(刚刚捕获了$ project部分):

{
"$project"=>{
     "paid_on" => {"$ifNull"=>["$paid_on", 1980-01-01 00:00:00 UTC]},
     "paid_amt" => 1
 }

并失败:

失败,错误16006:“异常:无法从BSON类型字符串转换为日期”

我已经尝试了其他几种方法来发送日期而没有运气:

  • 'ISODate( “1980-01-01”)'
  • {“$ date”=> 315554400000}

1 个答案:

答案 0 :(得分:1)

以下适用于我。我建议您重新创建它并查看它与您的代码的不同之处。

模型/应用/ claim.rb

class Claim
  include Mongoid::Document
  field :paid_on, type: Time
  field :paid_amt, type: Float
end

测试/单元/ claim_test.rb

require 'test_helper'
require 'pp'

class ClaimTest < ActiveSupport::TestCase
  def setup
    Claim.delete_all
  end

  test "replace null date field" do
    docs = [
        {
            :paid_on => DateTime.parse("2013-03-08T22:25:24.973Z"),
            :paid_amt => 25.5
        },
        {
            :paid_on => nil,
            :paid_amt => 12.25
        }
    ]
    Claim.create(docs)
    pipeline = [
        {
            "$project" => {
                "paid_on" => {"$ifNull" => ["$paid_on", Date.new(1980, 1, 1).mongoize]},
                "paid_amt" => 1
            }
        }
    ]
    puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
    puts "pipeline:#{pipeline.inspect}"
    pp Claim.collection.aggregate(pipeline)
  end
end

$ rake test

Run options: 

# Running tests:

[1/1] ClaimTest#test_replace_null_date_field
Mongoid::VERSION:3.1.5
Moped::VERSION:1.5.1
pipeline:[{"$project"=>{"paid_on"=>{"$ifNull"=>["$paid_on", 1980-01-01 00:00:00 UTC]}, "paid_amt"=>1}}]
[{"_id"=>"5272720a7f11ba4293000001",
  "paid_on"=>2013-03-08 22:25:24 UTC,
  "paid_amt"=>25.5},
 {"_id"=>"5272720a7f11ba4293000002",
  "paid_on"=>1980-01-01 00:00:00 UTC,
  "paid_amt"=>12.25}]
Finished tests in 0.039125s, 25.5591 tests/s, 0.0000 assertions/s.
1 tests, 0 assertions, 0 failures, 0 errors, 0 skips