C# 使用“ObjectId”查询 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14315684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Query MongoDB Using 'ObjectId'
提问by Mike Barnes
I have inserted document
s into MongoDB without an id
. And I want to retrieve them by searching through their MongoDB ObjectId
, that has been assigned in default.
我已将document
s插入到 MongoDB 中,而没有id
. 我想通过搜索默认分配的MongoDBObjectId
来检索它们。
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
发生“System.NullReferenceException”类型的第一次机会异常
What is the problem?
问题是什么?
采纳答案by soulcheck
You need to create an instance of ObjectId
and then query using that instance, otherwise your query compares ObjectId
s to string and fails to find matching documents.
您需要创建一个实例,ObjectId
然后使用该实例进行查询,否则您的查询会将ObjectId
s 与字符串进行比较并且无法找到匹配的文档。
This should work:
这应该有效:
var query_id = Query.EQ("_id", ObjectId.Parse("50ed4e7d5baffd13a44d0153"));
var entity = dbCollection.FindOne(query_id);
return entity.ToString();
回答by smakus
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):
选择的答案是正确的。对于那些对 Query.EQ 感到困惑的人,这里有另一种编写基本更新的方法(更新整个 mongodb 文档):
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.
当您要实际按对象 ID 进行搜索时,需要 ObjectId 对象,否则将 string 与 objectid 类型进行比较,将不匹配。Mongo 在这方面非常严格,无论字段名称是否正确。
回答by Minhas Kamal
In C#for latest official MongoDB.Driverwrite this-
在C# 中为最新的官方MongoDB.Driver写这个 -
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.
我们可以在不将id
字符串转换为ObjectId
. 但是,我们将不得不在模型类中添加[BsonRepresentation(BsonType.ObjectId)]
beforeid
属性。
The code can even be further simplified using lambda expression-
甚至可以使用lambda 表达式进一步简化代码-
var entity = dbCollection.Find(document => document.id == "50ed4e7d5baffd13a44d0153").FirstOrDefault();
return entity.ToString();
回答by Kdog
If you're here in 2018 and want copy/paste code that still works or pure string syntax;
如果您在 2018 年来到这里并希望复制/粘贴仍然有效的代码或纯字符串语法;
[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);
}
回答by Raul Baez
You can also do it this way, its
你也可以这样做,它的
public static ObjectId GetInternalId(string id)
{
if (!ObjectId.TryParse(id, out ObjectId internalId))
internalId = ObjectId.Empty;
return internalId;
}
then in your method you can do something like this
然后在你的方法中你可以做这样的事情
ObjectId internalId = GetMongoId.GetInternalId(id);
return await YourContext.YourTable.Find(c => c.InternalId == internalId).FirstOrDefaultAsync();
Note: id param in GetInternalId its a parameter on that method. In case you need as this:
注意:GetInternalId 中的 id 参数是该方法的一个参数。如果您需要这样:
public async Task<YourTable> Find(string id)
{
ObjectId internalId = GetMongoId.GetInternalId(id);
return await YourContext.YourTable.Find(c => c.InternalId == internalId).FirstOrDefaultAsync();
}
Hope it helps also.
希望它也有帮助。