如何在Javascript中从集合数组中提取键的值
我想从一系列集合中获取数组中键的值。请查找代码片段和预期输出。我会的 如果您能在聚合阶段帮助我获得所需输出,我将不胜感激。请注意,将有超过5000个集合如何在Javascript中从集合数组中提取键的值,javascript,mongodb,aggregation-framework,Javascript,Mongodb,Aggregation Framework,我想从一系列集合中获取数组中键的值。请查找代码片段和预期输出。我会的 如果您能在聚合阶段帮助我获得所需输出,我将不胜感激。请注意,将有超过5000个集合 db.collection1.insertMany([{ item: "journal", qty: 25, tags: blank }, { item: "mat", qty: 85, tags: gray }, { item: "mousepad", qty:
db.collection1.insertMany([{
item: "journal",
qty: 25,
tags: blank
},
{
item: "mat",
qty: 85,
tags: gray
},
{
item: "mousepad",
qty: 25,
tags: gel
}
])
db.collection2.insertMany([{
abc: "paplu",
qiity: 01,
thugs: red
},
{
abc: "mat",
qiity: 85,
thugs: gray
},
{
abc: "mousepad",
qiity: 25,
thugs: gel
}
])
var a = ["collection1", "collection2"];
for (var i = 0; i < a.length; i++) {
db[a[i]].aggregate([])};
Expected Output:
collection1
{
item : ["journal","mat","mousepad"],
qty : [25,85,25],
tags : [blank,gray,gel]
}
collection2
{
abc : ["paplu","mat","mousepad"],
qiity : [01,85,25],
thugs : [red,gray, gel]
}
Please note, I'm trying to achieve this using MongoDB/JavaScript
It would be great if someone can help me with this!
db.collection1.insertMany([{
项目:“日记账”,
数量:25,
标签:空白
},
{
物品:“垫子”,
数量:85,
标签:灰色
},
{
物品:“鼠标垫”,
数量:25,
标签:凝胶
}
])
db.collection2.insertMany([{
abc:“帕鲁”,
qiity:01,
暴徒:红色
},
{
abc:“垫子”,
年龄:85,
暴徒:灰色
},
{
abc:“鼠标垫”,
年龄:25,,
暴徒:凝胶
}
])
变量a=[“集合1”、“集合2”];
对于(变量i=0;i
您可以从开始将键从根对象
获取到数组中。然后,您可以运行并通过null
从整个集合中获取包含唯一键名的单个文档。在最后一步中,您需要使用和将数组转换回单个文档:
db.collection.aggregate([
{
$project: { kv: { $objectToArray: "$$ROOT" } }
},
{ $unwind: "$kv" },
{
$group: {
_id: null,
keys: { $addToSet: "$kv.k" }
}
},
{
$replaceRoot: {
newRoot: {
$arrayToObject: {
$map: { input: "$keys", in: [ "$$this", 1 ] }
}
}
}
}
])