Home > Enterprise >  Field combination in an array where another field is the same in MongoDB?
Field combination in an array where another field is the same in MongoDB?

Time:02-02

I want to find matches with the same gender and insert them into a new field array aka names but I am unable to solution using MongoDB. Or mongooese.

Input example:

db.students.insertMany([
  { id: 1, name: "Ryan", gender: "M" },
  { id: 2, name: "Joanna", gender: "F" },
  { id: 3, name: "Andy", gender: "M" },
  { id: 4, name: "Irina", gender: "F" }
]);

Desired output:

[
   { gender: "M", names: ["Ryan","Andy"]},
   { gender: "F", names: ["Joanna","Irina"]}
]

Note: the table has many records and I do not know those gender/name pairs in advance

I try this but no results. I don't know how I should write this query.

db.students.aggregate([
    {
        $group:{
            names : {$push:"$name"},
            }
        },
         { "$match": { "gender": "$gender" } }  

])

CodePudding user response:

You did not specify how to group. Try this one:

db.students.aggregate([
  {
    $group: {
      _id: "$gender",
      names: { $push: "$name" }      
    }
  },
  { 
    $set: { 
      gender: "$_id",
      _id: "$$REMOVE"
    } 
  }
])
  • Related