简体   繁体   English

如何在mongodb中的纯JSON中通过Id查询文档

[英]How to query document by Id in pure json in mongodb

In Mongodb (2.6.1), I need to query a document by _id using pure json (without using ObjectIds). 在Mongodb(2.6.1)中,我需要使用 json通过_id查询文档(不使用ObjectIds)。 As mentioned in the mongodb extended json , I was expecting db.collection.findOne({"_id": {"$oid": "51b6eab8cd794eb62bb3e131"}}) to work but it does not. mongodb扩展json中所述 ,我期望db.collection.findOne({"_id": {"$oid": "51b6eab8cd794eb62bb3e131"}})可以正常工作,但不能正常工作。 It even throw the following exception. 它甚至抛出以下异常。

Can't canonicalize query: BadValue unknown operator: $oid 无法规范化查询:BadValue未知运算符:$ oid

Anyone knows how to do it? 有人知道该怎么做吗?

The extended JSON syntax is intended as a "transfer" format so that if for example you are sending JSON ouput to a remote client there is still a way to determine the actual implemented type such as ObjectId, Date, Binary etc. 扩展的JSON语法旨在用作“传输”格式,因此,例如,如果您要将JSON输出发送到远程客户端,仍然可以通过一种方法来确定实际实现的类型,例如ObjectId,Date,Binary等。

The only place AFIAK where this is implemented is within the C# driver which provides a json parser utility method which would take JSON with the extended syntax fields and then "cast" those into objects of the required type. AFIAK唯一实现此功能的地方是C#驱动程序,该驱动程序提供json解析器实用程序方法,该方法将使用带有扩展语法字段的JSON,然后将其“投射”到所需类型的对象中。

So in much the same way you can implement your own parser routine to do much the same thing, it is just a matter of testing the key values for something that represents the type of object specified in the key. 因此,以几乎相同的方式,您可以实现自己的解析器例程以执行相同的操作,这只是测试代表键中指定的对象类型的键值的问题。 Given a sample fragment: 给定一个样本片段:

{ "_id": { "$oid": "51b6eab8cd794eb62bb3e131" } }

In simplified form without recursively checking by depth: 简化形式,无需递归检查深度:

data = JSON.parse( json );

for ( k in data ) {
    if ( data[k].hasOwnProperty("$oid") )
        data[k] = new ObjectId( data[k]["$oid"] );
    // etc
}

So just because you may be using JavaScript it doesn't mean the "extended syntax" is valid as a query source, but you can as with other languages post-process the parsed JSON into the valid object notation required by that language and the query interface. 因此,仅因为您可能正在使用JavaScript,并不意味着“扩展语法”可以作为查询源有效,但是可以像其他语言一样将解析后的JSON后处理为该语言和查询所需的有效对象符号接口。

Similar "casting" is performed by some drivers on "string" values supplied against an _id field in order to cast to the correct object type required by the BSON wire protocol. 一些驱动程序对_id字段提供的“字符串”值执行类似的“广播”,以便转换为BSON有线协议所需的正确对象类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM