繁体   English   中英

如何在 mongo db 中获取所有数字类型的属性?

[英]How do I get all attributes which are numeric types in mongo db?

我需要提取所有数字类型的属性。 例如,如果不同的属性是

{ 年龄:32 性别:“女性” 年份:2020 姓名:“Abc” }

我的查询应该返回 ["age","year"]

我认为以下查询应该可以帮助您。

db.test.aggregate([
    // Remove this `$limit` stage if your Collection schema is dynamic and you want to process all the documents instead of just one
    {
        "$limit": 1
    },
    {
        "$project": {
            "arrayofkeyvalue": {
                "$filter": {
                    "input": {"$objectToArray":"$$ROOT"},
                    "as": "keyValPairs",
                    "cond": {
                        "$in": [{"$type": "$$keyValPairs.v"}, ["double", "int", "long"]],
                        // Change the above line to the following to get only `int` keys instead of `int, double` and `long`:
                        // "$eq": [{"$type": "$$keyValPairs.v"}, "int"],
                    }
                }
            }
        }
    },
    {
        "$group": {
            "_id": null,
            "unique": {"$addToSet": "$arrayofkeyvalue.k"}
        }
    },
    {
        "$project": {
            "_id": 0,
            "intKeyNames": {
                "$reduce": {
                    input: "$unique",
                    initialValue: [],
                    in: {$setUnion : ["$$value", "$$this"]}
                }
            }
        }
    },
])

上面的查询结果会是这样的:

{
    "intKeyNames" : [
        "_id",
        "abc",
        "paymentMonth",
        "paymentYear",
        "value"
    ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM