Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Can't canonicalize query: BadValue unknown operator

Tags:

mongodb

The data is given as follows:

{
    "_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" ] 
}

But when I use the following command to find something, the error comes out

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

How can I find the document with specific $oid.

like image 836
Wyatt Avatar asked Jun 04 '15 14:06

Wyatt


2 Answers

You need to convert the id string to an ObjectId like this:

db.guardian.find({ "_id": ObjectId("546b79a2e4b0f7bfbaa97cc7") })

The reason being that { "$oid" : "546b79a2e4b0f7bfbaa97cc7"} is the same as ObjectId("546b79a2e4b0f7bfbaa97cc7") just in a different format.

Refer to the docs for more details.

like image 65
chridam Avatar answered Nov 18 '22 03:11

chridam


You can add below class methods to your model

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
like image 23
Niket Avatar answered Nov 18 '22 03:11

Niket