3

I have an array of id's authorIds=["1","2",3","4"]. I have another array that holds the reference to the authorIds. ex:

book=[
{
      bookId:"abcd",
      authorId:"1"
},
{
      bookId:"def",
      authorId:"1"
}
{
      bookId:"ghi",
      authorId:"2"
}
{
      bookId:"kjl",
      authorId:"1"
}
];

now i would like to use the In query (mongodb C# drvier) but want to restrict the number of books to 5 for each author. Can someone tell me how to do this.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Kiran P
  • 299
  • 2
  • 11
  • Possible duplicate of [limit and sort each group by in mongoDB using aggregation](http://stackoverflow.com/questions/33458107/limit-and-sort-each-group-by-in-mongodb-using-aggregation) – Blakes Seven Nov 11 '15 at 06:10

1 Answers1

1

You can use Limit option to achieve this:

var builder = Builders<Book>.Filter;
FilterDefinition<Book> filter = builder.In((b => b.authorId), authorIds);
var find = products.Find(filter);
find.Options.Limit = 5;

var bookList = find.ToListAsync().Result;

you can also combine SortBy to this:

var builder = Builders<Book>.Filter;
FilterDefinition<Book> filter = builder.In((b => b.authorId), authorIds);
var sorted = products.Find(filter).SortBy(b => b.bookId);
sorted.Options.Limit = 5;

var bookList = sorted.ToListAsync().Result;
jhmt
  • 1,401
  • 1
  • 11
  • 15