Hussein Menshawi
Hussein Menshawi

Reputation: 96

How to group a document with the same name that has different values for a specific attribute in one array using Mongodb?

If I have these objects :

{
    "_id" : ObjectId("5caf2c1642e3731464c2c79d"),
    "requested" : [],
    "roomNo" : "E0-1-09",
    "capacity" : 40,
    "venueType" : "LR(M)",
    "seatingType" : "TB",
    "slotStart" : "8:30AM",
    "slotEnd" : "9:50AM",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5caf2deb4a7f5222305b55d5"),
    "requested" : [],
    "roomNo" : "E0-1-09",
    "capacity" : 40,
    "venueType" : "LR(M)",
    "seatingType" : "TB",
    "slotStart" : "10:00AM",
    "slotEnd" : "11:20AM",
    "__v" : 0
}

is it possible to get something like this using aggregate in mongodb?

[{ roomNo: "E0-1-09" , availability : [{slotStart : "8:30AM", slotEnd: "9:50AM"} ,
{slotStart: "10:00AM", slotEnd : "11:20AM"}]

what im using currently:

db.getDB().collection(collection).aggregate([
  { $group: {_id:{roomNo: "$roomNo", availability :[{slotStart:"$slotStart", slotEnd:"$slotEnd"}]}}}
     ])

actually getting it twice like so :

[{ roomNo: "E0-1-09" , availability : [{slotStart : "8:30AM", slotEnd: "9:50AM"}]
[{ roomNo: "E0-1-09" , availability : [{slotStart: "10:00AM", slotEnd : "11:20AM"}]

Upvotes: 1

Views: 268

Answers (1)

Ashh
Ashh

Reputation: 46461

You have to use $push accumulator

db.collection.aggregate([
  { "$group": {
    "_id": "$roomNo",
    "availability": {
      "$push": {
        "slotEnd": "$slotEnd",
        "slotStart": "$slotStart"
      }
    }
  }}
])

Upvotes: 1

Related Questions