如何在不同的嵌套级别上搜索MongoDB-Documents?

时间:2015-07-30 09:50:11

标签: mongodb profiling profiler analysis nested

我目前正在分析一个system.profile - MongoDB数据库的集合。我想查找具有COLLSCAN oder IXSCAN的舞台的查询。我的问题是,字段stage可以在多个级别上发生(...:缩短的JSON):

{
    "op" : "query",
    "ns" : "spt.coll",
    "query" : {
        "user" : "userC"
    },
    "ntoreturn" : 1,
    ...
    "millis" : 0,
    "execStats" : {
        "stage" : "PROJECTION",
        "nReturned" : 1,
        ...
        "transformBy" : {
            "settings.arr" : 1
        },
        "inputStage" : {
            "stage" : "FETCH",
            "nReturned" : 1,
            ...
            "alreadyHasObj" : 0,
            "inputStage" : {
                "stage" : "IXSCAN",
                "nReturned" : 1,
                ...
                "matchTested" : 0
            }
        }
    },
    "ts" : ISODate("2015-07-30T09:16:22.551Z"),
    "client" : "127.0.0.1",
    "allUsers" : [ ],
    "user" : ""
}

在上面的例子中,阶段发生在3个级别:

  1. "execStats.stage"
  2. "execStats.inputStage.stage"
  3. "execStats.inputStage.inputStage.stage"
  4. 可能存在更深层次的嵌套阶段。 有没有办法返回所有文档,这些文档在任何嵌套级别上都有stage: "IXSCAN"stage: "COLLSCAN"或者我是否必须为每个嵌套级别运行查询?

    我尝试使用以下函数引用How to find MongoDB field name at arbitrary depth,但不幸的是,这会产生错误:

    db.system.profile.find(
      function () {
        var findKey = "stage",
            findVal = "COLLSCAN";
    
        function inspectObj(doc) {
          return Object.keys(doc).some(function(key) {
            if ( typeof(doc[key]) == "object" ) {
              return inspectObj(doc[key]);
            } else {
              return ( key == findKey && doc[key] == findVal );
            }
          });
        }
        return inspectObj(this);
      }
    )
    

    错误消息:

    Error: error: {
        "$err" : "TypeError: Object.keys called on non-object\n    at Function.keys (native)\n    at inspectObj (_funcs1:6:25)\n    at _funcs1:8:22\n    at Array.some (native)\n    at inspectObj (_funcs1:6:35)\n    at _funcs1:8:22\n    at Array.some (native)\n    at inspectObj (_funcs1:6:35)\n    at _funcs1 (_funcs1:14:16) near 'rn Object.keys(doc).some(function(key) '  (line 6)",
        "code" : 16722
    }
    

    要重现上述JSON,请使用以下代码:

    use spt
    
    db.coll.drop()
    
    db.coll.insert([
      {settings: {arr: ["a", "b"]}, user: "userA"},
      {settings: {arr: ["c", "d"]}, user: "userB"},
      {settings: {arr: ["e", "f"]}, user: "userC"},
      {settings: {arr: ["g", "g"]}, user: "userD"},
    ])
    
    db.coll.ensureIndex({user: 1})
    
    db.setProfilingLevel(0)
    db.system.profile.drop()
    db.setProfilingLevel(2)
    
    
    db.coll.find({user: "userC"}, {"settings.arr": 1}).limit(1).pretty()
    db.system.profile.find().pretty()
    

1 个答案:

答案 0 :(得分:1)

当对象不是可枚举的时,Object.keys会引发您提到的错误。 一种简单的方法是捕获并忽略错误:

db.system.profile.find(
  // Returns all documents, for which this function returns true.
  function () {
    var findKey = "stage",
        findVal = "COLLSCAN";

    function inspectObj(doc) {
      // Object.keys(doc) works only for enumerables like (Arrays and Documents)
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
      // The incoming Object might also be e.g. `ISODate("2015-07-29T08:20:42.768Z")`
      // Thus you need to catch (and ignore) TypeErrors thrown by Object.keys()
      var contains = false;
      try {
            contains = Object.keys(doc).some(function(key) {
              cVal = doc[key];
              if ( typeof(cVal) == "object" ) {
                // Recursive call if value is an Object.
                return inspectObj(doc[key]);
              } else {
                return ( key == findKey && doc[key] == findVal );
              }
            });
      } catch(TypeError) {
        // ignore TypeError
      }
      return contains;
    }

    return inspectObj(this);
  }, {op: 1, ns:1, query: 1}
)