Search code examples
mongodbmongoosesubdocument

Sorting a mongo db document on basis of a value in subdocument


I have a mongodb collection where a user data is in following format:

{"_id" : ObjectId("5eceb0917a6a4d37688687cf"),
    "iscontactVerified" : true,
    "posts" : [ 
        {
            "_id" : ObjectId("5eceb0917a6a4d37688687d1"),
            "title" : "dewf",
            "hash" : "d9bf9eea351b2096ef467fe659e6598615d88115d96125ee91f5cd516b331549",
            "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
            "date" : ISODate("2020-05-27T18:25:59.030Z"),
        }, 
        {
            "_id" : ObjectId("5eceb0917a6a4d37688687d0"),
            "title" : "dewf1",
            "hash" : "d9bf911eea351b2096ef467fe659e6598615d88115d96125ee91f5cd516b331549",
            "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
            "date" : ISODate("2020-05-29T18:25:59.072Z")
        },  
        {
            "_id" : ObjectId("5ede210480a94515c0a1bde9"),
            "title" : "dewf2",
            "hash" : "d9bf923dds11eea351b2096ef467fe659e6598615d88115d96125ee91f5cd516b331549",
            "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
            "date" : ISODate("2020-05-30T18:25:59.072Z")
        }    ],
   
    "email" : "[email protected]",
    "status" : "Active",
}

I have to find users whose any post have been published between start date and end date and then sort the users according to the post date in ascending or descending order.


Solution

  • The query bellow will get all the documents between startDate(sDate) and endDate(eDate). I suggest you do the sorting part in your node server.

    let users = await User.find({ "posts.date":{ $gte: sDate, $lte: eDate } })
    

    Otherwise you could go for mongodb aggregation. But I think the method above is sufficient.