gpt4 book ai didi

MongoDB : How can I project all field types for a single document?

转载 作者:行者123 更新时间:2023-12-02 00:18:33 24 4
gpt4 key购买 nike

我需要检查给定集合中每个文档中的每个字段类型。

虽然我可以为每个字段编写单独的 $type 命令并分别匹配每个文档,但我想知道是否有一种更优雅、更有效的方法来投影所有字段类型。

最佳答案

试试这个:

db.collection.aggregate([{
$addFields: {
types: {
$arrayToObject: {
$map:
{
input: { $objectToArray: "$$ROOT" },
as: "each",
in: { k: '$$each.k', v: { $type: '$$each.v' } }
}
}}
}
}])

收集数据:

/* 1 */
{
"_id" : ObjectId("5e065992400289966eefb9a8"),
"username" : "myName",
"blog" : "myBlog",
"details" : "myBlogDetails",
"Object" : {
"inOneObject" : true
}
}

/* 2 */
{
"_id" : ObjectId("5e0659ae400289966eefbc3a"),
"username" : "othersName",
"blog" : "not a blog",
"details" : "useless"
}

结果:

/* 1 */
{
"_id" : ObjectId("5e065992400289966eefb9a8"),
"username" : "myName",
"blog" : "myBlog",
"details" : "myBlogDetails",
"Object" : {
"inObject" : true
},
"types" : {
"_id" : "objectId",
"username" : "string",
"blog" : "string",
"details" : "string",
"Object" : "object"
}
}

/* 2 */
{
"_id" : ObjectId("5e0659ae400289966eefbc3a"),
"username" : "othersName",
"blog" : "not a blog",
"details" : "useless",
"types" : {
"_id" : "objectId",
"username" : "string",
"blog" : "string",
"details" : "string"
}
}

注意:此给定查询仅适用于文档中的顶级字段,它不会从下面的字段中获取 inObject 类型::

"Object" : {
"inOneObject" : true
}

关于MongoDB : How can I project all field types for a single document?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59937836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com