使用查询的MongoDB的ObjectId [英] Query MongoDB using ObjectId

查看:158
本文介绍了使用查询的MongoDB的ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经插入到文档的MongoDB没有ID,并想通过搜索自己的MongoDB的ObjectId以检索他们的MongoDB给的文件

I have inserted documents into mongodb without an id and would like to retrive them by searching for their MongoDB ObjectId that MongoDB has given the documents

下面是我的尝试:

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

我得到一个errror说:

I get an errror saying:

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

这是什么问题?

What is the problem?

推荐答案

您需要使用实例来创建的ObjectId 的一个实例,然后查询,否则您的查询比较的ObjectId s到字符串,并没有找到匹配的文件。

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.

这应该工作:

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

这篇关于使用查询的MongoDB的ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆