N
N
Ninazu2016-07-27 15:12:58
MongoDB
Ninazu, 2016-07-27 15:12:58

How to organize a search through subdocuments with an unknown intermediate node?

There is a structure:

{
  "A" : {
    "B1" : {
      "C" : {
        "K1" : {
          "x" : NumberLong(12),
          "y" : NumberLong(13)
        }
      }
    },
    "B2" : {
      "C" : {
        "K1" : {
          "x" : NumberLong(35),
          "y" : NumberLong(45)
        },
        "K2" : {
          "x" : NumberLong(1),
          "y" : NumberLong(0)
        }
      }
    }
  }
}

There is a task:
Select all K1 (the variable that is being passed) from all B n
I tried it myself but there are problems:
1. How to specify not explicitly B1 , but all B n
2. How to push the name of the key B n into the category result
.aggregate([
    {$match:{
        "A.B1.C.K1":{
            $exists:true
        }
    }},
    {$project:{
        "result":"A.B1.C.K1",
        "category":"B1",
        "_id":false
    }}
]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2016-07-27
@lega

Probably at you not search, and search. You can use map-reduce, you can get all the documents and iterate over manually.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question