0

使用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_onnull,但我也需要捕获这些文档,所以我试图使用$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 }
4

1 回答 1

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

$耙子测试

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
于 2013-10-31T15:07:36.940 回答