gpt4 book ai didi

java - 集合 Mongo 中所有文档中字段的超集

转载 作者:可可西里 更新时间:2023-11-01 10:21:45 26 4
gpt4 key购买 nike

假设所有文档的类型相同但字段数量不同,如何在单个 MongoDB 集合中的所有文档中创建一组超字段(_id 除外)。

示例:

doc1 - {"_id":"test1", "firstName":"sample1", "age":24, "state":"Kansas"}
doc2 - {"_id":"test2", "lastName":"sample2", "age":24, "country":"US"}

super 集将是:{"firstName", "lastName", "age", "state", "country"

最佳答案

您可以尝试运行一个 mapReduce 操作,该操作将返回输入集合中所有给定的文档键 作为结果的 _id 键文档。这将在输出集合中,然后您可以在 _id 字段上应用 distinct 命令以检索字段的超集。

下面的例子展示了这个概念:

// Run mapReduce on collectionName
String map = "function () { for (var key in this) { emit(key, null); } }";
String reduce = "function () {}";
MapReduceResults<ValueObject> results = mongoTemplate.mapReduce(
"collectionName",
map,
reduce,
new MapReduceOptions().outputCollection("col_out"),
ValueObject.class
);
// Get the distinct keys from output collection col_out ---
List<String> fieldsSuperset = mongoTemplate.getCollection("col_out").distinct("_id");

关于java - 集合 Mongo 中所有文档中字段的超集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38789136/

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