【问题标题】:Get documents with unique field - Mongoid获取具有唯一字段的文档 - Mongoid
【发布时间】:2015-09-10 11:16:36
【问题描述】:

我有一个带有item_id 字段的ratings 集合。我需要检索具有不同 item_id 字段的所有文档。例如,假设我有这些文件:

{item_id: "123", some_other_field: "bla,bla"}
{item_id: "123", some_other_field: "bla,bla"}
{item_id: "121", some_other_field: "bla,bla"}
{item_id: "120", some_other_field: "bla,bla"}

我需要的结果:

{item_id: "123", some_other_field: "bla,bla"}
{item_id: "121", some_other_field: "bla,bla"}
{item_id: "120", some_other_field: "bla,bla"}

我怎样才能做到这一点?我看到this 的问题,他们提出 map-reduce 作为解决方案,但它应该更容易!

谢谢。

【问题讨论】:

    标签: ruby mongodb mongoid mongodb-query aggregation-framework


    【解决方案1】:

    如果您在此处的“意思”是“完全不同”的文档,那就容易多了。但是你这里基本上需要的是.aggregate(),特别是$group

    Model.collection.aggregate([
        { "$group" => {
            "_id" => {
                "item_id" => "$item_id",
                "some_other_field" => "$some_other_field"
            }
        }}
    ])
    

    或者,如果您只想在“一个”字段上“区分”,那么类似:

    Model.collection.aggregate([
        { "$group" => {
            "_id" => "$item_id",
            "some_other_field" => { "$first" => "$some_other_field" }
        }}
    ])
    

    这些不再是 mongoid “文档”,但如果结构相同,您始终可以将它们“转换”回来,这可以通过一些操作或 $project 管道阶段来实现。

    Model.collection.aggregate([
        { "$group" => {
            "_id" => "$item_id",
            "some_other_field" => { "$first" => "$some_other_field" }
        }},
        { "$project" => {
            "_id" => 0,
            "item_id" => "$_id",
            "some_other_field" => "$some_other_field"
        }}
    ])
    

    还要提一下,这比 mapReduce 快“显着”,因为代码使用 MongoDB 的本地运算符并且没有 JavaScript 翻译。

    阅读operators for aggregation pipelines 作为您可以做的事情的一般指南。

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 2011-10-23
      • 2014-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 2021-11-15
      相关资源
      最近更新 更多