MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Contare il numero di istanze di stringa in un campo tra i documenti raggruppati in un altro campo in MongoDB?

Puoi provare sotto la query:

db.collection.aggregate([
    /** Group all docs based on flightNum & status & count no.of occurances */
    {
        $group: {
            _id: {
                flightNum: "$flightNum",
                status: "$status"
            },
            count: {
                $sum: 1
            }
        }
    },
    /** Group on flightNum & push an objects with key as status & value as count */
    {
        $group: {
            _id: "$_id.flightNum",
            status: {
                $push: {
                    k: "$_id.status",
                    v: "$count"
                }
            }
        }
    },
    /** Recreate status field as an object of key:value pairs from an array of objects */
    {
        $addFields: {
            status: {
                $arrayToObject: "$status"
            }
        }
    },
    /** add flightNum inside status object */
    {
        $addFields: {
            "status.flightNum": "$_id"
        }
    },
    /** Replace status field as new root for each doc in coll */
    {
        $replaceRoot: {
            newRoot: "$status"
        }
    }
])

Test : MongoDB-Playground