2

Let's take a collection named values which contains the following documents.

{ "_id" : 1, "name" : "value1", "x" : 1, "y" : 2 }
{ "_id" : 2, "name" : "value1", "x" : 2, "y" : 2 }
{ "_id" : 3, "name" : "value1", "z" : 10 }
{ "_id" : 4, "name" : "value1", "z" : 20 }
{ "_id" : 5, "name" : "value2", "x" : 8, "y" : 3 }
{ "_id" : 6, "name" : "value2", "x" : 8, "y" : 3 }
{ "_id" : 7, "name" : "value2", "z" : 15 }

Here, if I query based on name, take value1, then I should get the following single document.

{ "name" : "value1", "x" : [ 1, 2 ], "y" : [ 2, 2 ], "z" : [ 10, 20 ] }

I think this has something to do with aggregation. But I have no idea how to do it. Is there any way to achieve this behavior?

1 Answer 1

2

You can use below aggregtion

db.collection.aggregate([
  {
    $match: {
      name: "value1"
    }
  },
  {
    $group: {
      _id: "$name",
      x: {
        "$push": "$x"
      },
      y: {
        "$push": "$y"
      },
      z: {
        "$push": "$z"
      }
    }
  }
])

MongoPlayground

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

4 Comments

Is it possible to add a name field to the resulting document?
Yeah. But what if I match the documents using multiple common fields like name and I want to include them in the resulting document?
I got it. If we use $first, we can still have the fields we want.
@L.ShaneJohnPaulNewton Yes stackoverflow.com/questions/54440636/…

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.