我正在使用 mongoid 进行 mongodb 聚合,使用ModleName.collection.aggregate(pipeline). 返回的值是一个数组而不是 a Mongoid::Criteria,因此如果 afirst对数组执行 a 操作,我会得到第一个类型的元素BSON::Document而不是ModelName。结果,我无法将其用作模型。
是否有一种方法可以从聚合中返回条件而不是数组,或者将 bson 文档转换为模型实例?
使用 monoid (4.0.0)
我自己也一直在为此苦苦挣扎。恐怕你必须自己建立你的“模型”。让我们以我的代码为例:
class Searcher
# ...
def results(page: 1, per_page: 50)
pipeline = []
pipeline <<
"$match" => {
title: /#{@params['query']}/i
}
}
geoNear = {
"near" => coordinates,
"distanceField" => "distance",
"distanceMultiplier" => 3959,
"num" => 500,
"spherical" => true,
}
pipeline << {
"$geoNear" => geoNear
}
count = aggregate(pipeline).count
pipeline << { "$skip" => ((page.to_i - 1) * per_page) }
pipeline << { "$limit" => per_page }
places_hash = aggregate(pipeline)
places = places_hash.map { |attrs| Offer.new(attrs) { |o| o.new_record = false } }
# ...
places
end
def aggregate(pipeline)
Offer.collection.aggregate(pipeline)
end
end
Run Code Online (Sandbox Code Playgroud)
我从原始项目中省略了很多代码,只是为了展示我一直在做的事情。
这里最重要的是这行:
places_hash.map { |attrs| Offer.new(attrs) { |o| o.new_record = false } }
Run Code Online (Sandbox Code Playgroud)
我创建了一个数组Offers,但另外,我手动将它们的new_record属性设置为false,因此它们的行为就像通过简单的任何其他文档一样Offer.where(...)。
它并不漂亮,但它对我有用,而且我可以充分利用整个聚合框架!
希望有帮助!
| 归档时间: |
|
| 查看次数: |
1640 次 |
| 最近记录: |