gpt4 book ai didi

Ruby mongoid 聚合返回对象

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:41 27 4
gpt4 key购买 nike

我正在使用 mongoid 进行 mongodb 聚合,使用 ModleName.collection.aggregate(pipeline) 。返回的值是一个数组而不是 Mongoid::Criteria,所以如果对数组执行 first,我会得到类型为 的第一个元素>BSON::Document 而不是 ModelName。因此,我无法将其用作模型。

是否有一种方法可以从聚合中返回条件而不是数组,或者将 bson 文档转换为模型实例?

使用 mongoid (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

我从原始项目中省略了很多代码,只是为了展示我一直在做的事情。

这里最重要的是一行:

places_hash.map { |attrs| Offer.new(attrs) { |o| o.new_record = false } }

我正在创建一个 Offers 数组,但另外,我手动将它们的 new_record 属性设置为 false,所以它们的行为与通过简单的 Offer.where(...) 获得的任何其他文档一样。

它不漂亮,但对我有用,我可以充分利用整个聚合框架!

希望对您有所帮助!

关于Ruby mongoid 聚合返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389105/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com