简体   繁体   English

如何从 Javascript 中的集合数组中提取键的值

[英]How to extract values of the Keys from an array of collections in Javascript

I want to get the values of the keys in an array from a series of collection.我想从一系列集合中获取数组中键的值。 Please find the snippet of code and expected output.请找到代码片段和预期输出。 I would be grateful if you can help me with what should go into the aggregate phase to get the desired output.如果您能帮助我解决应该进入聚合阶段以获得所需输出的内容,我将不胜感激。 Please note there will be more than 5000 collections请注意将有超过 5000 个集合

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!


You can start with $objectToArray to get keys from ROOT object into an array.您可以从$objectToArray开始将键从ROOT对象获取到数组中。 Then you can run $unwind and $group by null with $addToSet to get single document which contains unique key names from entire collection.然后,您可以使用$addToSet运行$unwind$group by null以获取包含整个集合中唯一键名称的单个文档。 In the last step you need to convert an array back to single document using $map , $arrayToObject and $replaceRoot :在最后一步中,您需要使用$map$arrayToObject$replaceRoot将数组转换回单个文档:

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 ] }
                }
            }
        }
    }
])

Mongo Playground蒙戈游乐场

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

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