Sunday, April 4, 2021

Flatten array in MongoDb ($unwind) vs HCL Notes (View)

 Let's say you have an array dataset:

[{

    "name": "Simon",

    "hobbies": ["badminton", "tennis"]

},{

    "name": "Max",

    "hobbies": ["swimming", "tennis"]

}]


You can fatten the hobbies array to multiple documents using $unwind.


db.hobby.aggregate([{$unwind : "$hobbies"}]).pretty()


The result:

[{

        "_id" : ObjectId("6066d4146fc1865ad270a066"),

        "name" : "Simon",

        "hobbies" : "badminton"

},

{

        "_id" : ObjectId("6066d4146fc1865ad270a066"),

        "name" : "Simon",

        "hobbies" : "tennis"

},

{

        "_id" : ObjectId("6066d42b6fc1865ad270a067"),

        "name" : "Max",

        "hobbies" : "swimming"

},

{

        "_id" : ObjectId("6066d42b6fc1865ad270a067"),

        "name" : "Max",

        "hobbies" : "tennis"

}]


Let produce the same data set in HCL Notes.


In the columns property, set "Ascending" sort and check to "Show multiple values as separate entries".


The result:



After splitting the array data into a different document, we can group them to get to the sum. For example, we would like to get to the total number of each hobby. 

In MongoDb, here is the query:

db.hobby.aggregate([
{$unwind : "$hobbies"},
{$group: { _id : '$hobbies',count: { $sum: 1 }}}
]).pretty()

The result:

{ "_id" : "badminton", "count" : 1 }
{ "_id" : "tennis", "count" : 2 }
{ "_id" : "swimming", "count" : 1 }

In HCL Notes, category (group) the hobbies column. 


Add a new column with below setting:


The result:


No comments:

Post a Comment