Home > other >  MongoDB: Variable nested in several objects
MongoDB: Variable nested in several objects

Time:09-22

I have a problem creating a query in MongoDB. I have the following JSON. How to ask mongodb question to get _id from level5 object?

{
  "Id": "1",
  "level1": {
    "level2": {
      "level3": {
        "level4": {
          "level5": {
            "_id": 2
          }
        }
      }
    }
  }
}

CodePudding user response:

You can use the dot notation to get value from nested object:

db.collection.aggregate([
    {
        $project: {
            value: "$level1.level2.level3.level4.level5._id"
        }
    }
])

Mongo Playground

CodePudding user response:

I don't think I expressed myself very well. It is important for me to get the value of the variable "_id" from the "level5" object, but you have to assume that the object is still nests. For example:

{
  "Id": "1",
  "level1": {
    "level2": {
      "level3": {
        "level4": {
          "level5": {
            "_id": 2,
            "level6": {
              "level7": {
                "_id": 3,
                ...
              }
            }
          }
        }
      }
    }
  }
}

I just want "_id". The best method if possible is of course

  • Related