从数组列表中获取唯一的数组

时间:2014-03-23 05:47:55

标签: mongodb mongoid

我有以下数组,我需要从数组列表中获取唯一数组或设置联合(仅相同的一次),并且还排除空数组。如何在服务器端实现这一目标?

 
{
    "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"]
}

1 个答案:

答案 0 :(得分:0)

通过使用.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 }}
])

请注意,“set”不被视为由引擎的内部命令。如果您需要要订购的结果,则可以再次$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 }}
])

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

相关问题