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'))




2023-01-07

Python - Insert Pandas dataframe row at the end

 df.loc[len(df.index)] = YOUR_LIST

Pymongo - Insert current timestamp as ISODate

from pymongo import MongoClient

import datetime



client = MongoClient("mongodb://YOUR_CONNECTION_STRING")

db = client.YOUR_DATABASE_NAME

collection = db.YOUR_COLLECTION_NAME


# Truncate

collection.delete_many({})


# Date treatment

date = datetime.datetime.utcnow()

at = datetime.datetime.strptime(

    str(date),

    "%Y-%m-%d %H:%M:%S.%f"

)


# Insertion

collection.insert_one({"YOUR_FIELD_NAME": at})


2023-01-03

Python - How to unite two dataframes

 import pandas as pd


df1 = pd.DataFrame()

df2 = pd.DataFrame()

df3 = pd.concat([df1, df2])