簡體   English   中英

如何從 Javascript 中的集合數組中提取鍵的值

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

我想從一系列集合中獲取數組中鍵的值。 請找到代碼片段和預期輸出。 如果您能幫助我解決應該進入聚合階段以獲得所需輸出的內容,我將不勝感激。 請注意將有超過 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!


您可以從$objectToArray開始將鍵從ROOT對象獲取到數組中。 然后,您可以使用$addToSet運行$unwind$group by null以獲取包含整個集合中唯一鍵名稱的單個文檔。 在最后一步中,您需要使用$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 ] }
                }
            }
        }
    }
])

蒙戈游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM