Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MongoDB Using 'ObjectId'

I have inserted documents into MongoDB without an id. And I want to retrieve them by searching through their MongoDB ObjectId, that has been assigned in default.

Here is my attempt-

var query_id = Query.EQ("_id", "50ed4e7d5baffd13a44d0153");
var entity = dbCollection.FindOne(query_id);
return entity.ToString();

And I get following error-

A first chance exception of type 'System.NullReferenceException' occurred

What is the problem?

like image 855
Mike Barnes Avatar asked Jan 14 '13 09:01

Mike Barnes


People also ask

What is the use of ObjectID in MongoDB?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

How do I query data in MongoDB?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.

How do I find the document ID in MongoDB?

Use the print() function to display the id of document.


Video Answer


4 Answers

You need to create an instance of ObjectId and then query using that instance, otherwise your query compares ObjectIds to string and fails to find matching documents.

This should work:

var query_id = Query.EQ("_id", ObjectId.Parse("50ed4e7d5baffd13a44d0153"));
var entity = dbCollection.FindOne(query_id);
return entity.ToString();
like image 94
soulcheck Avatar answered Sep 28 '22 16:09

soulcheck


In C# for latest official MongoDB.Driver write this-

var filter_id = Builders<MODEL_NAME>.Filter.Eq("id", ObjectId.Parse("50ed4e7d5baffd13a44d0153"));
var entity = dbCollection.Find(filter).FirstOrDefault();
return entity.ToString();

We can accomplish the same result without converting id from string to ObjectId. But then, we will have to add [BsonRepresentation(BsonType.ObjectId)] before id attribute in the model class.

The code can even be further simplified using lambda expression-

var entity = dbCollection.Find(document => document.id == "50ed4e7d5baffd13a44d0153").FirstOrDefault();
return entity.ToString();
like image 35
Minhas Kamal Avatar answered Sep 28 '22 15:09

Minhas Kamal


If you're here in 2018 and want copy/paste code that still works or pure string syntax;

    [Fact]
    public async Task QueryUsingObjectId()
    {
        var filter = Builders<CosmosParkingFactory>.Filter.Eq("_id", new ObjectId("5b57516fd16cb04bfc35fcc6"));
        var entity = stocksCollection.Find(filter);
        var stock = await entity.SingleOrDefaultAsync();
        Assert.NotNull(stock);

        var idString = "5b57516fd16cb04bfc35fcc6";
        var stringFilter = "{ _id: ObjectId('" + idString + "') }";
        var entityStringFiltered = stocksCollection.Find(stringFilter);
        var stockStringFiltered = await entityStringFiltered.SingleOrDefaultAsync();
        Assert.NotNull(stockStringFiltered);
    }
like image 40
Kdog Avatar answered Sep 28 '22 17:09

Kdog


The selected answer is correct. For anyone confused by the Query.EQ, here is another way to write a basic update (updates the entire mongodb document):

string mongoDocumentID = "123455666767778";
var query = new QueryDocument("_id", ObjectId.Parse(mongoDocumentID)); 
var update = new UpdateDocument { { "$set", documentToSave } };
mongoCollection.Update(query, update, UpdateFlags.Multi);

The ObjectId object is needed when you want to actually search by object ID, otherwise it is comparing string to objectid type, and it won't match. Mongo is very type-strict in this way, regardless if the field name is correct.

like image 21
smakus Avatar answered Sep 28 '22 17:09

smakus