How to remove an item from a collection with C#

6,137 views
Skip to first unread message

darrellj

unread,
Aug 5, 2011, 2:00:42 PM8/5/11
to mongodb-user
Hello,

I have a form that a person can search from. I can return the users
back and I take the ObjectId and pass it to a textbox. Then when a
user clicks the Delete Button, I want to remove the collection item
with that ID. I'm doing some thing wrong and I'm very new to Mongo.
Below is the copy of my delete function. Any suggestions would be
great....


protected void deleteUser(object sender, EventArgs e)
{
var mongo = new Mongo();
mongo.Connect();

var db = mongo.GetDatabase("gac_corp_db");
var categories = db.GetCollection("user_collection");

//build a new doc with the Object Id that was stored in
the text box
var spec = new Document();
spec["_id"] = txtuid.Text.ToString();

categories.Remove(spec);


mongo.Disconnect();
}

Robert Stam

unread,
Aug 5, 2011, 2:16:21 PM8/5/11
to mongodb-user
What version of the C# driver are you using?

With the official C# driver you would write something like this:

var id = ObjectId.Parse(txtuid.Text);
var query = Query.EQ("_id", id);
collection.Remove(query);

Don't call Disconnect because that will interfere with connection
pooling.

darrellj

unread,
Aug 5, 2011, 2:37:23 PM8/5/11
to mongodb-user
Thanks for the reply. I'm using version 1.8.2.

I tried your example, but it wanted a Document Selector passed to the
Remove method? Here is my new code:

protected void deleteUser(object sender, EventArgs e)
{
var mongo = new Mongo();
mongo.Connect();

var db = mongo.GetDatabase("gac_corp_db");
var categories = db.GetCollection("user_collection");

var id = ObjectId.Parse(txtuid.Text.ToString());
var query = Query.EQ("_id", id);

//right here it will not compile because of a document
selector
categories.Remove(query);

Robert Stam

unread,
Aug 5, 2011, 2:53:37 PM8/5/11
to mongodb-user
Are you sure you are using the official version of the C# driver?

1.8.2 is a server version. The current version of the C# driver is
1.1.

Information on downloading the official C# driver is at:

http://www.mongodb.org/display/DOCS/CSharp+Language+Center

darrellj

unread,
Aug 5, 2011, 3:55:22 PM8/5/11
to mongodb-user
Thanks and I'm sorry. I've been on this for a week and this all is
just so very new to me. Ok, so I got the right version, but I have
another question. How can I find a record when searching for a name?
Simple, I know, but really I have looked at so many different forums
and examples, I really just need someone to say, this is how you do
it. I have this much so far:

protected void findUser(object sender, EventArgs e) {
var mongo = new Mongo();
var db = mongo.GetDatabase("gac_corp_db");
var users = db.GetCollection("user_collection");

//searches for a name that was entered in to this txtbox
var query = Query.EQ("name", txtsearch.Text.ToString());

//down here I want to display the results in a label

Robert Stam

unread,
Aug 5, 2011, 4:03:22 PM8/5/11
to mongodb-user
Once you have defined a query you use it to Find the document:

var query = Query.EQ("name", somestring);
var document = collection.FindOne(query);

I recommend you start by reading the online tutorial:
'
http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial

darrellj

unread,
Aug 5, 2011, 4:07:53 PM8/5/11
to mongodb-user
Thanks for your reply. I have read this documentation. I guess I'm
just not understanding this at all. I'll try to re-read this and see
if anything makes sense again.

Robert Stam

unread,
Aug 5, 2011, 4:14:42 PM8/5/11
to mongodb-user
OK. Here's some more sample code for you to look at while you read the
documentation.

var server = MongoServer.Create();
var database = server["gac_corp_db"];
var collection = database["user_collection"];
var query = Query.EQ("name", "Robert");
var document = collection.FindOne(query);
var name = document["name"].AsString; // name should now equal
"Robert"
var city = document["address"].AsBsonDocument["city"].AsString;

The query describes which document you want to Find. The Find method
actually reads it from the database and returns it as a BsonDocument,
and the following statements extract pieces of the document out. This
is assuming that the document looks something like this:

{
name : "Robert",
address : {
"line1" : "123 Main St",
"city" : "Smallville"
}
}

Feel free to follow up with more questions as you read through the
tutorial.

darrellj

unread,
Aug 5, 2011, 4:31:33 PM8/5/11
to mongodb-user
Thanks Robert. Ok, so after further review I am able to insert and
remove records! But now comes the question of updating a record. Now,
again I've read the documentation, but when you have time please
review this;

protected void updateUser(object sender, EventArgs e)
{
MongoServer server = MongoServer.Create();
MongoDatabase db = server.GetDatabase("gac_corp_db");

var users = db.GetCollection("user_collection");
var id = ObjectId.Parse(txtuid.Text.ToString());
var query = Query.EQ("_id", id);

//users.Remove(query); works!

var update = Update.Set("name", txtname.Text.ToString());

//when I try to do this it says that "Cannot implicitly
convert MongoDB.Driver.SafeModeResult to MongoDB.Bson.BsonDocument"
BsonDocument updateComplete = users.Update(query, update);

}

Thanks for all of your help on this...

darrellj

unread,
Aug 5, 2011, 4:41:25 PM8/5/11
to mongodb-user
Robert,

I got it! THANK YOU! I don't know if this is the best way to do it or
not but it works! I borrowed the code from above so it looks like this


protected void updateUser(object sender, EventArgs e)
{
MongoServer server = MongoServer.Create();
MongoDatabase db = server.GetDatabase("gac_corp_db");

var users = db.GetCollection("user_collection");
var id = ObjectId.Parse(txtuid.Text.ToString());
var query = Query.EQ("_id", id);

//users.Remove(query); works!

foreach (BsonDocument user in users.Find(query)) {
user["name"] = txtname.Text.ToString();
user["company"] = txtcompanyname.Text.ToString();
users.Save(user);
}

}

If you have time, let me know if this is OK or a total HACK!

Robert Stam

unread,
Aug 5, 2011, 4:47:01 PM8/5/11
to mongodb-user
Looks OK. If you used FindOne instead of Find you might not need a
foreach loop. But if you are expecting multiple documents to match
then a foreach loop is appropriate (but I don't see how you could
match multiple documents in this particular example since you are
querying on the _id and that is guaranteed to be unique).

The difference between Save and Update is that Save sends the entire
changed document to the server, and Update sends instructions on how
to update one or more fields. Save is much easier to use, but Update
can be more efficient when documents are really large and you are only
updating a few fields or when you need atomic updates.

darrellj

unread,
Aug 5, 2011, 5:10:30 PM8/5/11
to mongodb-user
Thanks again Robert. I did look at the example code and it gave me an
error when I tried to use the update. With the example that I
provided, the one that works, how could you apply the update?

darrellj

unread,
Aug 5, 2011, 5:12:00 PM8/5/11
to mongodb-user
Thanks again Robert. I looked at the example code and I tried to do
what they did but it wouldn't compile. How could I apply the changes
using update with the current code that I posted last?

Robert Stam

unread,
Aug 5, 2011, 5:17:53 PM8/5/11
to mongodb-user
To use Update it would look something like this:

var updates = Update.Set("name",
txtname.Text.ToString()).Set("company",
txtcompanyname.Text.ToString());
var result = collection.Udpate(query, updates);

The datatype of result is SafeModeResult (not BsonDocument).

darrellj

unread,
Aug 5, 2011, 5:34:08 PM8/5/11
to mongodb-user
Thank you Sir!
> ...
>
> read more »
Reply all
Reply to author
Forward
0 new messages