【问题标题】:MongoDB query - Select one of each from non unique arrayMongoDB查询 - 从非唯一数组中选择一个
【发布时间】:2013-08-30 12:14:36
【问题描述】:

我有一个具有以下架构的集合:

{ 
    _id: 521cc63c19752c562300001a,
    author: 'John',
    quote: 'A quote',
    type: 1,
    stars:
     [{ _id: 521cc63c19752c562300001b,
       user: 521cc63c19752c5623000003,
       date: Tue Aug 27 2013 16:31:08 GMT+0100 (IST) }]
}

我正在尝试选择在特定数组中具有类型的文档。例如,如果类型是唯一的,它会返回每个类型的三个引号,完全符合预期:

db.quotes.aggregate([
    {$match: {
        "type": {
            $in: [1, 2, 3] //The unique types
        }
    }},

    // Group by the type
    {$group: {
        _id: "$type",
        id: { $first: "$_id" },
        author: { $first: "$author" },
        stars: { $first: "$stars" },
        description: { $first: "$description" }
    }},

    // Map/project the first result of each group
    // to their respective keys
    {$project: {
        _id: "$id",
        type: "$_id",
        author: "$author",
        description: "$description"
        stars: "$stars"
    }}
]);

我的问题是类型可能并不总是唯一的。我可能必须找到三个具有相同类型的文档([1, 1, 1])或两个相同且一个唯一的文档([1, 2, 2])。当出现这种情况时,由于 $group by type 管道命令,它只会返回一两个结果。有什么建议我可以提供三种非唯一类型并始终得到每种类型的三个引号?

【问题讨论】:

  • 要么你应该从你的查询中删除 $groupby 步骤,要么我没有正确理解你。
  • @Shad 然后它返回所有具有该类型的文档,而不仅仅是每个文档。我可以看到我是如何暗示的,我将编辑我的问题。谢谢。

标签: mongodb mongoose aggregation-framework nosql


【解决方案1】:

您需要编写自己的函数:

  • 将您的 types 数组作为参数。
  • 实例化一个空的 skipDocs 哈希/对象,例如

    var objSkipDocs = {};

  • 对于 types 数组的每个元素,将散列中该值的键归零。

    for (var i = 0; i

  • 对于您的 types 数组的每个元素,尝试获取一个文档,例如

    db.quotes.findOne({'type': arrayTypes[i] }).skip(objSkipDocs[arrayTypes[i]]);

    objSkipDocs[ arrayTypes[i] ] += 1;

  • 对检索到的文档做一些事情

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 2017-10-10
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多