mongo-csharp-driver, how to use $slice for array, how to return selected field in find

830 views
Skip to first unread message

mamu

unread,
Nov 9, 2010, 11:20:13 PM11/9/10
to mongodb-user
Question 1:

I have a document which has a array field. I can't figure out how to
use $slice with C# driver.
I want to get last 10 entries.

Could you please let me know how to do it? I have gone through whole
c# driver document there is no mention of it.


Question 2:
find methods in c# driver only takes query, how can specify field
names i need to retrieve?
I have very large document so trying to avoid getting whole document
with find.

Robert Stam

unread,
Nov 10, 2010, 12:24:49 AM11/10/10
to mongodb-user
Question 1:

The easiest way is:

var query; // your query
var slice = Fields.Slice("arrayField", -10);
var cursor = collection.Find(query).SetFields(slice);
foreach (var document in cursor) {
// process document
}

You can also create the slice specification directly if you prefer:

var slice = new BsonDocument("arrayField", new BsonDocument("$slice",
-10));

Question 2:

The easiest way is:

var query; // your query
var fields = Fields.Include("field1", "field2", ...);
var cursor = collection.Find(query).SetFields(fields);
foreach (var document in cursor) {
// process document
}

You can also create the slice specification directly if you prefer:

var fields = new BsonDocument { { "field1", 1 }, { "field2",
1 }, ... };

Max Voronoy

unread,
Feb 9, 2014, 7:46:57 AM2/9/14
to mongod...@googlegroups.com
Robert answered nice for question 2. Let me answer after 3 years modern vision of your first question.
C# driver now support following syntax (my example stores last 10 QueryTime of UserVisit):

   var update = Update<UserVisit>
                    .Inc(i => i.Count, 1)
                    .PushEach(i => i.QueryTime,
                        options => options.Slice(-10),
                        user.QueryTime );

After that apply update:

Collection
                    userVisitCol.FindAndModify(
                        query/*find what to update*/, 
                        null,  
                        update, false/*return new*/, true/*upsert*/
                    );
Reply all
Reply to author
Forward
0 new messages