3

My class:

class Product
{
    public string _id {get; set;}
    public IEnumerable<Item> Items {get; set;}
    public int ItemsCount {get; set;}
}

class Item
{
    public string Name {get; set;}
}

I need to select Items only and process skip limit (paging) for them. Count I can store in the object. Is it possible to use mongo for that or should I put Items to another collection?

1 Answer 1

4

we can have two scenarios here:

  1. We are always requesting ONE main document and need to have skip/limit on this particular array.

  2. We are requesting an unknown number of documents and then we could do skip/limit on a kind of merged array from all source ones.

Both solutions are using aggregation framework with $unwind stage, the diffrence is that $match in first case always returns only one document (let's say matched by objectId).

var aggregate = collection.Aggregate().Match(x => x.Id == ourNeededId)
     .Unwind("Items").Skip(3).Limit(3).Project<Product>(project);

As output we will get 3 documents which we can a) merge using $group server side or iterate and process in c# code.

EDIT

        var aggregate =
            collection.Aggregate()
                .Match(x => x._id == "some id here")
                .Unwind("Items")
                .Skip(3)
                .Limit(3)
                .Group(BsonDocument.Parse("{_id:{id:'$_id', ItemsCount:'$ItemsCount' },Items:{$push:'$Items'} }"))
                .Project<Product>(BsonDocument.Parse("{_id:'$_id.id', ItemsCount:'$_id.ItemsCount', Items:1  }"))
                .ToList();

Any comments welcome!

2
  • Thanks a lot! Could you, please, provide any example of group code? Jul 7, 2016 at 9:39
  • Thanks for your time! Jul 7, 2016 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.