3

I have tried limiting the Group by data on Mongo DB 3.0 but seems like there is no proper option to do this.

I want to display 5 latest records for each day based on this date dateCreated which is in array and corresponding records count/day

db.entries.find().limit(1).pretty();
{
    "_id" : "bd348fb4dd38dd7a2",
    "className" : "com.model.Entry",
    "name" : "yQLs3T5NCJocPlOPuLgyEkQ9",
    "description" : "4Z09BNPQNFhFiMbjqL RWC5SMs0d0XzogqdNmjk5dx1mw9roHgRrl8ljbHo16p1WTlNYU",
    "account" : DBRef("accounts", "248a3-448b-a912-6573f23d34a5"),
    "iconUrl" : "gA9QTuqYv9wZq1xKM37jdL",
    "userCreatedBy" : DBRef("users", "8044-45d2-8567-a6cb808ce164"),
    "timezone" : "Atlantic/Faroe",
    "globalAccess" : false,
    "tags" : [
        {
            "_id" : "8926079483331",
            "category" : "PPq5k",
            "value" : "NdKFQq",
            "description" : "uDQVnhJ2tu5XWHinb",
            "origin" : "User",
            "dateCreated" : ISODate("2021-07-16T18:20:41.731Z"),
            "dateModified" : ISODate("2021-07-16T18:20:53.319Z"),
            "externalId" : "xkblzrwE"
        }
{
            "_id" : "89389483331",
            "category" : "PPe5k",
            "value" : "NdKFQq",
            "description" : "uDQVnhJ2tu5XWHinb",
            "origin" : "User",
            "dateCreated" : ISODate("2021-07-16T18:20:41.731Z"),
            "dateModified" : ISODate("2021-07-16T18:20:53.319Z"),
            "externalId" : "xkblzrwE"
        }
]}

Output I'm expecting this :

[2021-07-16 (Date)-> (5 Latest Entries) , 2 (total records for that day) ]

I have tried using below solution How to get lastest N records of each group in mongodb?

and slice is not available on mongo 3.0 i'm kind of stuck here

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
ranjan
  • 31
  • 2

1 Answers1

1

I'm not sure you can use aggregation but below aggregation can give you the result you wanted.

db.collection.aggregate([
  {
    "$unwind": "$tags"
  },
  {
    $match: {
      "tags.dateCreated": {
        "$gte": ISODate("2021-07-16")
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$tags"
    }
  },
  {
    "$limit": 5
  }
])

Playground

If you have any question feel free to ask me, please.

Murat Colyaran
  • 2,075
  • 2
  • 8
  • 27
  • I have to display 5 latest records for every day and count of records for the day but your query fetch only for specified date – ranjan Jul 21 '21 at 09:28
  • It fetches the last 5 records that are greater than the date you specified. You didn't specify any scripting language. If you create a `for` loop or something that updates the `date` field dynamically you can achieve what you wanted. Otherwise, it'd be much much harder to create a dynamic loop on the mongodb side. If you're using node.js I can give you an example. – Murat Colyaran Jul 21 '21 at 10:53
  • replaceRoot is inroduced in 3.4 and we are still on 3.0 MongoDb – ranjan Jul 22 '21 at 08:01