gpt4 book ai didi

ruby-on-rails - Mongoid:按字段排序并跳过N条记录

转载 作者:可可西里 更新时间:2023-11-01 09:12:30 25 4
gpt4 key购买 nike

我有一个包含以下数据的集合:

{
"_id" : ObjectId("516b969beceaed363a000027"),
"user" : "276",
"item" : "796",
"rating" : 1,
}

我想按 user 排序,然后在每个用户中,我想跳过前 10 条记录,只返回其他记录。如果用户没有 10 条记录,则不应返回任何内容。我还需要反过来:按用户排序,只返回前 10 条记录。如果用户没有 10 条记录,它应该返回例如 6 条记录。

我不知道如何在不调用 ruby​​ 脚本的情况下在 Mongoid 中执行此操作。有什么想法吗?

最佳答案

假设您已经定义了一个映射到该集合的模型:

class MyModel
include Mongoid::Document

field :user, type: String
field :item, type: String
field :rating, type: Integer
end

那么你要找的查询就很简单了:

#  I want to order by user and then within each user, I want to skip the first 10 records, and only return the other records
MyModel.asc(:user).skip(10)

# Order by user and only return the first 10 records. If a user doesn't have 10 records, it should return for example 6 records
MyModel.asc(:user).limit(10)

注意这两个查询都返回 Mongoid Criteria 对象。如果您需要实际的数组 - 在结果上调用 to_a

关于ruby-on-rails - Mongoid:按字段排序并跳过N条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16190251/

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