MongoDB:无法规范化查询:BadValue未知运算符

12

数据如下:

{
    "_id" : { "$oid" : "546b79a2e4b0f7bfbaa97cc7" }, 
    "title" : "Eyewitness: Highlands, Scotland", 
    "description" : "Photographs from the Guardian Eyewitness series", 
    "timeStamp" : "14/11/2014", 
    "category" : "news", 
    "url" : "http://www.theguardian.com/world/picture/2014/nov/14/1", 
    "source" : "http://www.theguardian.com/",
    "mainStory" : "\n",
    "keywords" : [ "Wildlife", "Scotland" ] 
}

但是当我使用以下命令查找某些内容时,就会出现错误

db.guardian.find({ "_id": {"$oid": '546b79a2e4b0f7bfbaa97cc7'}})

我如何找到具有特定$oid的文档。

2个回答

8
您需要将 id 字符串转换为 ObjectId,方法如下:
db.guardian.find({ "_id": ObjectId("546b79a2e4b0f7bfbaa97cc7") })

原因是{"$oid": "546b79a2e4b0f7bfbaa97cc7"}ObjectId("546b79a2e4b0f7bfbaa97cc7")是相同的,只是格式不同。

请参考文档了解更多细节。


1
如果您正在使用Node.js,则还需要使用var ObjectId = require('mongodb').ObjectID; 要求 ObjectID。 - strttn

1
您可以在您的模型中添加以下类方法。
def self.serialize_from_session(key, salt)
  (key = key.first) if key.kind_of? Array
  (key = BSON::ObjectId.from_string(key['$oid'])) if key.kind_of? Hash

  record = to_adapter.get(key)
  record if record && record.authenticatable_salt == salt
end

def self.serialize_into_session(record)
  [record.id.to_s, record.authenticatable_salt]
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接