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:
$group
- Group byparagraph
and$push
text
into array field (texts
).$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.$sort
- Sort byid
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
}
}
])