Take a unique array from a list of arrays

I have the following array, I need to get unique arrays or set union (the same thing only once) from the list of arrays, and also exclude empty arrays. How can this be achieved on the server side?

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

I need a conclusion like,

{
    "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"]
}
+4
source share
1 answer

The result can be achieved using a method .aggregate()that allows pipeline operations to act on an element on the "forms" of the data. The most important one here is $addToSetthat contains only the "unique / identical" elements:

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 }}
])

, . , , , , .

0

Source: https://habr.com/ru/post/1533032/


All Articles