首页 > 解决方案 > MongoDB聚合将列表转换为布尔值

问题描述

我需要在 MongoDB 中进行查询,根据列表中是否存在值,我将列表转换为 True 或 False。

这是架构的总结视图。

{'_id': ObjectId('604edf91571e7ab19cc2c238'),
 'timestamp': 1616164767.773929,
 'name': 'some name',
 'metric1': 1,
 'metric2': 2,
 'metric3': 3,
 'tags': ['tag1', 'tag2', 'tag3', 'tag that matters']}

'tag that matters'如果 a在列表中,有没有办法将 tags 键更改为 True 或 False 的值?我不想排除没有标签的记录,我只想让这些记录的标签键值为 False。

标签: mongodbmongodb-queryaggregation-framework

解决方案


试试这个查询:

db.collectionName.aggregate([
    {
        "$addFields": {
            "tags": {
                $map: {
                    input: "$tags",
                    as: "tag",
                    in: {
                        $eq: ['$$tag', 'tag that matters']
                    }
                }
            }
        }
    }
]);

输出:

{
    "_id" : ObjectId("604edf91571e7ab19cc2c238"),
    "timestamp" : 1616164767.773929,
    "name" : "some name",
    "metric1" : 1,
    "metric2" : 2,
    "metric3" : 3,
    "tags" : [
        false,
        false,
        false,
        true
    ]
}

推荐阅读