1

I am new to NoSQL databases and MongoDb. I've got the following question:

I have a collection of such documents:

{
  vals: [
    {
      value: 111,
      timestamp: 1563454669669
    },
    {
      value: 222,
      timestamp: 1563454689665
    },
    {
      value: 333,
      timestamp: 1563454669658
    }
    .......
  ]
}

I would like to convert it into the following documents using aggregation pipeline:

{
  vals: [
    [
      111,
      1563454669669
    ],
    [
      222,
      1563454689665
    ],
    [
      333,
      1563454669658
    ]
    .......
  ]
}

After years of work with relational databases, it's quite hard to understand..

1 Answer 1

2

You can use $map operator to transform one array into another array:

db.collection.aggregate([
    {
        $project: {
            vals: {
                $map: {
                    input: "$vals",
                    in: [ "$$this.value", "$$this.timestamp" ]
                }
            }
        }
    }
])

Mongo Playground

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

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.