vbNewbie
vbNewbie

Reputation: 3345

mongodb query to get field only in .NET code

Can anyone help to get the correct .NET (C# or VB.NET) of the following query:

> db.usercollection.find( {}, { username:1, _id: 0 } )
   { "username" : "testuser1" }
   { "username" : "testuser2" }
   { "username" : "testuser3" }

Basically I only want to return certain fields of the document. Also is there anyway mongodb c# driver will convert the result into a json format that can populate a grid (extjs grid) or chart, without me doing the conversion explicitly.

 Using mongo.RequestStart(db)
        Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()
        Dim collection3 = db.GetCollection(Of BsonDocument)("usercollection").
                        Find({}, {"username:1", "_id:0"})

The collection3 line is not correct.

Tried the following too:

        For Each ruleSet In collection
            Dim rules As String = ruleSet.GetValue(0).AsString
            response = rules & response
        Next

But this gives error:

UNABLE TO CAST OBJECT OF TYPE 'MONGODB.BSON.BSONOBJECTID TO TYPE MONGODB.BSON.BSONSTRING

Upvotes: 2

Views: 2178

Answers (1)

i3arnon
i3arnon

Reputation: 116596

If you want to limit the results to specific fields you need to use SetFields on the MongoCursor like so:

MongoCursor<BsonDocument> cursor = _db.GetCollection<BsonDocument>.FindAll(); // or any other query
cursor.SetFields("username");

MongoD uses BSON which means Binary JSON. If you want to use it as a JSON use the extension method:

BsonDocument document;
document.ToJson();

Upvotes: 2

Related Questions