2023-03-29

MongoDB - Array of strings to comma-separated string, with no comma after the last element

 db.COLLECTION_NAME.aggregate([

    {$addFields: {

        "CONCATENATED_STRING": {$reduce: {

            "input": "$ARRAY_OF_STRINGS_FIELD_NAME",

            "initialValue": "",

            "in": {

                "$concat": [

                    "$$value",

                    {"$cond": [{"$eq": ["$$value", ""]}, "", ", "]}, 

                    "$$this"

                ]

            }

        }}

    }}    

]);

MongoDB - Array of strings to comma-separated string

 db.COLLECTION_NAME.aggregate([

    {$addFields: {

        "CONCATENATED_STRING": {$reduce: {

            "input": "$ARRAY_OF_STRINGS_FIELD_NAME",

            "initialValue": "",

            "in": {

                "$concat": [

                    "$$value",                    

                    "$$this",

                    ", ",

                ]

            }

        }}

    }}    

]);

2023-02-22

Minimongo - How to cast a date typed as an object, to an actual date type

 db.COLLECTION.update(

    {

        $expr: {$eq: [{"$type": "$YOUR_DATE_FIELD"}, "object"]},

    },

    {$set: {

        "YOUR_DATE_FIELD": new Date(parseInt("$YOUR_DATE_FIELD.$date.$numberLong")),

    }},

    {

        multi: true, 

        upsert: false,

    }

);



Original issue: 

Uncaught MinimongoError: Key $date must not start with '$'


2023-01-18

MongoDB - Count the number of fields or keys in a sub-document

 db.COLLECTION_NAME.aggregate([

    {$addFields: {

        'SUB_DOCUMENT_FIELD_COUNT': 

        {$size

        {$objectToArray

        {$ifNull[

                                    "$YOUR_FIELD", 

                                    {}

        ]}

        }

        },

}},

]);

MongoDB - Count the number of fields or keys in a document

 db.COLLECTION_NAME.aggregate([

    {$addFields: {

        'THIS_DOCUMENT_KEY_COUNT': {$size: {$objectToArray: "$$ROOT"}},

}},

]);

2023-01-08

Python - How to create a dataframe with a matrix of random numbers

 import pandas as pd

import numpy as np

from tabulate import tabulate


# 100 rows, 3 columns, random numbers

df = pd.DataFrame(

        np.random.rand(100, 3),

        columns=['COLUMN_1', 'COLUMN_2', 'COLUMN_3']

    )


# Pretty-print it

print(tabulate(df, headers='keys', tablefmt='grid', showindex='always'))