Home > Enterprise >  MongoDB: Filter and merge document with common field
MongoDB: Filter and merge document with common field

Time:11-07

Let's say i have 4 documents inside 1 collection

{
    id: 1,
    text: "Some text",
    paragraph: 1
}

{
    id: 2,
    text: "This has field paragraph 2",
    paragraph: 2
}

{
    id: 3,
    text: "This also has paragraph 2 field",
    paragraph: 2
}

{
    id: 4,
    text: "Some other text",
    paragraph: 3
}

Desired output of filter result must be

{
    id: 1,
    text: "Some text",
    paragraph: 1
}
{
    id: 2,
    text: "This has field paragraph 2 This also has paragraph 2 field",
    paragraph: 2
}
{
    id: 3,
    text: "Some other text",
    paragraph: 3
}

How to filter mongodb collection to get the results aforementioned or any other way to generate a collection with desired results and send that as a response.

CodePudding user response:

  1. $group - Group by paragraph and $push text into array field (texts).
  2. $project - Decorate output document. Use $reduce to $concat texts array field into string. And don't forget to use $trim to remove the starting whitespace.
  3. $sort - Sort by id ascending.
db.collection.aggregate([
  {
    $group: {
      _id: "$paragraph",
      texts: {
        "$push": "$text"
      }
    }
  },
  {
    $project: {
      _id: 0,
      id: "$_id",
      paragraph: "$_id",
      text: {
        $trim: {
          input: {
            $reduce: {
              "input": "$texts",
              "initialValue": "",
              "in": {
                $concat: [
                  "$$value",
                  " ",
                  "$$this"
                ]
              }
            }
          }
        }
      }
    }
  },
  {
    $sort: {
      id: 1
    }
  }
])

Sample Mongo Playground

  • Related