1

Below is the mongodb collection sample data. I'm trying to fire a query which will return and array of a property in my collection.

Sample Docs :

{
    "_id" : ObjectId("5e940d6c2f804ab99b24a633"),
    "accountId" : ObjectId("7e1c1180d59de1704ce43557"),
    "description":"some desc",
    "configs": {},
    "dependencies" : [ 
        {
            "commute" : {},
            "distance" : {},
            "support":{}
        }
    ]
}

Expected output :

{
    [0]:commute
    [1]:distance
    [2]:support
}

I've tried to get the response and iterate the dependencies object also I tried using es6 to convert it to an array object. But it is an expensive operation as this list would be really large. If at all there exists and such approach in Mongo to convert the response into array

3
  • Did you try aggregation pipeline? Commented Apr 13, 2020 at 12:14
  • So you just want the names of keys in dependencies field into an array ? Commented Apr 13, 2020 at 15:07
  • @whoami - yes, whatever keys are there Im trying get it as an array Commented Apr 13, 2020 at 15:19

2 Answers 2

1

You can try below aggregation query :

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      dependenciesKeys: {
        $reduce: {
          input: "$dependencies", // Iterate over 'dependencies' array
          initialValue: [],
          in: {
            $concatArrays: [ /** concat each array returned by map with holding 'value */'
              "$$value",
              {
                $map: {
                  input: {
                    $objectToArray: "$$this" /** Convert each object in 'dependencies' to array [{k:...,v:...},{k:...,v:...}] & iterate on each object */
                  },
                  in: "$$this.k" // Just return keys from each object
                }
              }
            ]
          }
        }
      }
    }
  }
])

Test : MongoDB-Playground

Ref : $reduce , $map , $concatArrays , $objectToArray & $project

Sign up to request clarification or add additional context in comments.

Comments

0

I think you should try Object to array, which is an aggregation pipeline operator.

Also the Aggregation Pipeline is pretty useful concept, it makes you create a pipeline of operations that process your data sequentially. You can imagine it as following; you create a steps 'Pipeline' every step make a certain operation 'Aggregate operation' in your data, which results to some certain data shape,like an array as you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.