SaNdY
SaNdY

Reputation: 508

How to get oldest record in mongodb group in side the grouped record?

I have set of records and try to get unique record for each row and unique record is the group, query is

db.collection.aggregate([
{ 
    $match : { 
        userId: 16,
        userListId : ObjectId('5b7e85f956de7e6ead026e23') ,

    } 
},
{
    $group: 
    {
        _id: '$domain',
        "websites": { $push: {
            '_id' : '$_id',
            'userId' : '$userId',
            'userListId' : "$userListId",
            'createdAt' : '$createdAt'
        }}
    }
}

]);

For the same domain i have 4 rows which are

{
        "_id" : ObjectId("5b7e55bb0f81ba2c5b0b54c8"),
        "userId" : 16,
        "userListId" : ObjectId("5b7e85f956de7e6ead026e23"),
        "createdAt" : 1535006139565.0
    }, 
    {
        "_id" : ObjectId("5b7e55bb0f81ba2c5b0b54a9"),
        "userId" : 16,
        "userListId" : ObjectId("5b7e85f956de7e6ead026e23"),
        "createdAt" : 1535006139564.0
    }, 
    {
        "_id" : ObjectId("5b7e55bb0f81ba2c5b0b54b4"),
        "userId" : 16,
        "userListId" : ObjectId("5b7e85f956de7e6ead026e23"),
        "createdAt" : 1535006139565.0
    }, 
    {
        "_id" : ObjectId("5b7e55bb0f81ba2c5b0b54c4"),
        "userId" : 16,
        "userListId" : ObjectId("5b7e85f956de7e6ead026e23"),
        "createdAt" : 1535006139565.0
    }

In the above records second record is first one from the database and i want to get it on first position, how can i do that?

"_id" : ObjectId("5b7e55bb0f81ba2c5b0b54a9")

I want above record on first position

Upvotes: 1

Views: 598

Answers (1)

Akrion
Akrion

Reputation: 18515

You could simply begin your pipeline the $sort operator:

db.collection.aggregate([
  {
    $match: {
      userId: 16,
      userListId: ObjectId("5b7e85f956de7e6ead026e23"),

    }
  },
  {
    $sort: {
      "createdAt": 1
    }
  },
  {
    $group: {
      _id: "$domain",
      "websites": {
        $push: {
          "_id": "$_id",
          "userId": "$userId",
          "userListId": "$userListId",
          "createdAt": "$createdAt"
        }
      }
    }
  }
])

See it working here

Note: Updated as per @chridam suggestion. Thanks.

Upvotes: 4

Related Questions