【问题标题】:Take an unique array from list of arrays从数组列表中获取唯一数组
【发布时间】:2014-03-23 05:47:54
【问题描述】:

我有以下数组,我需要从数组列表中获取唯一数组,或 set union (相同的东西只有一次),并且还排除空数组。这在服务器端如何实现?

{
    "slots": [
        [],
        ["08:30AM", "08:40AM", "08:50AM", "09:00AM", "09:10AM", "09:20AM", "09:30AM", "09:40AM", "09:50AM", "10:00AM", "10:10AM", "10:20AM", "10:30AM", "10:40AM", "10:50AM", "11:00AM", "11:10AM", "11:20AM", "11:30AM"],
        ["08:30AM", "08:40AM", "08:50AM", "09:00AM", "09:10AM", "09:20AM", "09:30AM", "09:40AM", "09:50AM", "10:00AM", "10:10AM", "10:20AM", "10:30AM", "10:40AM", "10:50AM", "11:00AM", "11:10AM", "11:20AM", "11:30AM"],
        ["08:30AM", "08:40AM", "08:50AM", "09:00AM", "09:10AM", "09:20AM", "09:30AM", "09:40AM", "09:50AM", "10:00AM", "10:10AM", "10:20AM", "10:30AM", "10:40AM", "10:50AM", "11:00AM", "11:10AM", "11:20AM", "11:30AM"],
        [],
        [],
        []
    ],
    }

我需要输出,

{
    "slots": [
        ["08:30AM", "08:40AM", "08:50AM", "09:00AM", "09:10AM", "09:20AM", "09:30AM", "09:40AM", "09:50AM", "10:00AM", "10:10AM", "10:20AM", "10:30AM", "10:40AM", "10:50AM", "11:00AM", "11:10AM", "11:20AM", "11:30AM"]
}

【问题讨论】:

  • 显示你做了什么。这不是一个把你的工作扔给其他人的地方。还添加了更多的标签,如 C、C++、javascript、java、function、php 和 python 等。
  • @SalvadorDali 虽然我同意“不要让别人做你的工作”的观点。 一种使用 MongoDB 执行此操作的明确方法,因此您希望在代码中执行此客户端,因此这些标记无关紧要。出于这个原因,持有也是如此。考虑到不是每个人都能说一口流利的英语。
  • 如果我的英语比打字好,可能会有所帮助:“不要让别人做你的工作”。但这可能是缺乏了解从哪里开始。问题的编辑内容应该足够清楚,以便给出 MongoDB 的答案。

标签: mongodb mongoid


【解决方案1】:

使用.aggregate() 方法可以实现结果,该方法允许管道操作作用于元素以“重新形成”数据。这里最重要的运算符是$addToSet,它只保留“唯一/相同”的元素:

db.slots.aggregate([

    // Unwind the "slots" array
    { "$unwind": "$slots" },

    // Unwind the "inner" arrays
    { "$unwind": "$slots" },

    // Compose a "set" of the results
    { "$group": { 
        "_id": null,
        "slots": { "$addToSet": "$slots" } 
    }},

    // Just return the "set"
    { "$project": { "_id": 0, "slots": 1 }}
])

请注意,“集合”不被认为是按引擎内部排序的。如果您需要对结果进行排序,那么您可以再次$unwind,对结果进行排序并重新分组。如下:

db.slots.aggregate([

    // Unwind the "slots" array
    { "$unwind": "$slots" },

    // Unwind the "inner" arrays
    { "$unwind": "$slots" },

    // Compose a "set" of the results
    { "$group": { 
        "_id": null,
        "slots": { "$addToSet": "$slots" } 
    }},

    // Unwind the "set" result
    { "$unwind": "$slots" },

    // Sort the results
    { "$sort": { "slots": 1 } },

    // Group the array again
    { "$group": {
        "_id": null,
        "slots": { "$push": "$slots" } 
    }},

    // Just return the "set"
    { "$project": { "_id": 0, "slots": 1 }}
])

您应该非常小心地存储这样的嵌套数组。除非您出于特殊目的特别需要,否则它们很难查询和更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2019-08-27
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多