如何查询mongodb以获取以下格式的数据?

时间:2019-06-13 07:22:55

标签: python mongodb pymongo

预期的查询输出

food = {
    'fruit': ['apple', 'banana', 'cherry'],
    'vegetables': ['onion', 'cucumber'],                                                 
}

数据库中的数据格式

    [{
    "category": "fruit",
    "name": "banana"
}, {
    "category": "fruit",
    "name": "apple"
}, {
    "category": "fruit",
    "name": "cherry"
}, {
    "category": "vegetables",
    "name": "onion"
}, {
    "category": "vegetables",
    "name": "cucumber"
}]

基本上,我需要从mongodb中获取不同的类别和名称列表。

TIA

1 个答案:

答案 0 :(得分:2)

db.collection.aggregate([{
        "$group": {
            "_id": "$category",
            "list": {
                "$addToSet": "$name"
            }
        }
    },
    {
        "$addFields": {
            "array": [{
                "k": "$_id",
                "v": "$list"
            }]
        }
    },
    {
        "$replaceRoot": {
            "newRoot": {
                "$arrayToObject": "$array"
            }
        }
    }
])

工作,例如https://mongoplayground.net/p/bccPDlORK7W