How to get last n subdocument in MongoDB?

107 views Asked by At

I want to find a document with Id=A then sort and take the subdocument inside document A. But I can't find any solution for it, especially in MongoDB.Driver for c#. At the document level we have a query like this:

db.foo.find().sort({_id:1}).limit(50);

But I need to apply the limit function for subdocuments, not documents.

consider this model as an example:

{
"_id" : "10000",
"password" : "password1",
"name" : "customer1",
"channels" : [ 
    {
        "id" : "1",
        "name" : "cust1chan1",
        "enabled" : true
    }, 
    {
        "id" : "2",
        "name" : "cust1chan2",
        "enabled" : true
    }, 
    {
        "id" : "3",
        "name" : "cust1chan2",
        "enabled" : true
    }, 
    {
        "id" : "4",
        "name" : "cust1chan2",
        "enabled" : true
    },...
]}

and I like my result to be something similar to this:

{
"_id" : "10000",
"password" : "password1",
"name" : "customer1",
"channels" : [ 
    {
        "id" : "1",
        "name" : "cust1chan1",
        "enabled" : true
    }, 
    {
        "id" : "2",
        "name" : "cust1chan2",
        "enabled" : true
    }
]}
1

There are 1 answers

0
Pooria On BEST ANSWER

I find the solution. We could use the Slice function in Projection. Something like this:

            var filter = Builders<Foo>.Filter.Where(p => p.Id == fooId);
            var slice = Builders<Foo>.Projection.Slice(p => p.Channels, 0, 2);
            var sort = Builders<Foo>.Sort.Descending("Foo.Channels");
            var articleDocument = _collectionFoo.Find(filter).Sort(sort).Project<Foo>(slice).FirstOrDefault();