0

I need to convert a mongo document in Angular, into an array of key value pairs like shown below. e.g. when a client document is recd, the whole document needs to be converted into an array as shown below.

There is an aggregation option in MongoDb - $objectToArray

{ $objectToArray: { item: "foo", qty: 25 } }

result:

[
   {
      "k" : "item",
      "v" : "foo"
   },
   {
      "k" : "qty",
      "v" : 25
   }
]
  1. I could not find this in Mongoose documentation? Is it available?

  2. Is there a way to achieve this in Angular when the document is received from Node API?

1 Answer 1

1

Yes, you can use $objectToArray in the aggregation pipeline and it will also work in mongoose, you try a query like this

Model.
  aggregate([{
        $project: { sampleField: { $objectToArray: "$array" } }
  }]).exec();

In case, if you want to convert the whole document into an array you can try this pipeline

db.collection.aggregate([
  {
    "$match": {
      _id: 1
    }
  },
  {
    // Add this stage in
    //case you want to exclude some keys
    "$project": {
      _id: 0
    }
  },
  {
    $project: {
      data: {
        $objectToArray: "$$ROOT"
      }
    }
  }
])

Here is a link to test the query in the playground: Mongo Playground

OR

If you want to do it in Angular then you can try this code

let object = { item: "foo", qty: 25 }

let result = Object.entries(object)
                   .map(itr => {
                      return {k: itr[0], v: itr[1]}
                    })

console.log(result)

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

4 Comments

Thanks a lot. I will try both. For the $objectToArray method, how do I apply it on the whole document - not a property? This will be on Model.findById(id). Basically, I will find a client by Id and then want to convert the client Object to Array.
Can you share some sample data, query and expected result? I will try to compose the query accordingly
const client = await Client.findById(id).select({ __v: 0 }).lean().exec() return client; This is my query. The result is a simple object(not a mongoose model). As of now I will use the Angular method suggested by you to convert the returned Client object into array. My Client Model has too many fields, hence, it will not be advisable to use that. Its a flat model, does not have nested properties.
Okay... I have updated my answer with a query and playground

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.