【问题标题】:MongoDB Query to find out all the array elements of a collectionMongoDB查询找出集合的所有数组元素
【发布时间】:2013-03-21 10:13:03
【问题描述】:

我有一个非常大的 MongoDB 文档,其中包含各种数据。我需要识别集合中数组类型的字段,以便我可以从我将填充的网格中显示的字段中删除它们。

我的方法现在包括检索集合中的所有字段名称

这取自MongoDB Get names of all keys in collection此处发布的回复

mr = db.runCommand({
  "mapreduce" : "Product",
  "map" : function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce" : function(key, stuff) { return null; }, 
  "out": "things" + "_keys"
})

db[mr.result].distinct("_id")

并为每个字段运行一个这样的查询

db.Product.find( { $where : "Array.isArray(this.Orders)" } ).count()

如果检索到任何内容,则该字段被视为数组。

我不喜欢我需要运行 n+2 个查询(n 是我的集合中不同字段的数量),我不想对模型中的字段进行硬编码。它会破坏使用 MongoDB 的全部目的。

有更好的方法吗?

【问题讨论】:

    标签: php mongodb mongodb-php nosql


    【解决方案1】:

    我对您上面提供的代码做了一些细微的修改:

    mr = db.runCommand({
      "mapreduce" : "Product",
      "map" : function() {
        for (var key in this) { 
           if (Array.isArray(this[key])) {
              emit(key, 1); 
           } else {
              emit(key, 0);
           }
        }
      },
      "reduce" : function(key, stuff) { return Array.sum(stuff); }, 
      "out": "Product" + "_keys"
    })
    

    现在,映射器将为包含数组的键发出 1,为不包含数组的键发出 0。 reducer 会将这些总结起来,以便在您检查最终结果时:

    db[mr.result].find()
    

    您将看到您的字段名称以及其中包含数组值的文档数量(以及任何不是数组的 0)。

    所以这应该会告诉你哪些字段包含数组类型,只需要 map-reduce 作业。

    --

    只是用一些数据来看看它:

    db.Product.insert({"a":[1,2,3], "c":[1,2]})
    db.Product.insert({"a":1, "b":2})
    db.Product.insert({"a":1, "c":[2,3]})
    

    (现在运行上面的“mr =”代码)

    db[mr.result].find()
    { "_id" : "_id", "value" : 0 }
    { "_id" : "a", "value" : 1 }
    { "_id" : "b", "value" : 0 }
    { "_id" : "c", "value" : 2 }
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2019-10-20
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多