Question

I have this collection:

Books
[
{
  _id: ObjectId(1),
  Title: Book1,
  Price: 100,
  Tags: ["A", "B", "C"] 
},
{
  _id: ObjectId(2),
  Title: Book2,
  Price: 200,
  Tags: ["C", "D", "E"] 
}
]

I want to return only _id field and the first element from the Tags array

So my result should look like this:

Books
[
{
  _id: ObjectId(1),
  Tags: ["A"] 
},
{
  _id: ObjectId(2),
  Tags: ["C"] 
}
]

The Tags array can be big and I only need to know what is at the first position.

var query = Query.EQ(<My condition here>);
var slice = Fields.Slice("Tags", 1);

return Books.FindAs<MyBookClass>(query).SetFields(slice).ToList(); <- Selects all fields from the document
return Books.FindAs<MyBookClass>(query).SetFields(slice).SetFields("_id", "Tags").ToList(); <- I am get _id but I also everything from the Tags array

This works nicely in command shell. How do I implement this using CSharp driver?
> db.Books.find({ "Price" : 100},{Tags:{$slice:1}, _id:1})

Is there a way to specify the Slice and the fields I want to read?

Was it helpful?

Solution

Below works for me, in Javascript Native code for MongoShell.

You can translate to C#

db.books.find({},{"Tags":{$slice:1},_id:1})

EDIT

What about this?

var query = Query.EQ(<My condition here>);
var slice = Fields.Slice("Tags", 1);
var fields = Fields.Include("_id","Tags"); 
return Books.FindAs<MyBookClass>(query).SetFields(fields).SetFields(slice).ToList(); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top