Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $oid vs ObjectId

Tags:

mongodb

mlab

I'm trying to get mongodb query working. Collection comes in the format:

{
"_id": {
    "$oid": "54651022bffebc03098b4567"
},
"browser": "ie",
"browser_version": "10.0 Desktop",
"os_version": "8",
"device": null,
"os": "Windows"
}

The following works:

{
    "_id": {
        "$in": [
            {
                "$oid": "54651022bffebc03098b4567"
            },
            {
                "$oid": "54651022bffebc03098b4568"
            }
        ]
   }
}

However, I get a syntax error for the following:

{
    "_id": {
        "$in": [
            ObjectId("54651022bffebc03098b4567"),
            ObjectId("54651022bffebc03098b4568")
        ]
    }
}

There are a similar questions that suggested that ObjectId should work:

How to create query with ObjectIds using java?

$all parameter in mongodb does not work with ObjectId list

like image 578
Vlad Vinnikov Avatar asked Nov 14 '14 20:11

Vlad Vinnikov


People also ask

What is $OID in MongoDB?

An ObjectID is a 12-byte Field Of BSON type. The first 4 bytes representing the Unix Timestamp of the document. The next 3 bytes are the machine Id on which the MongoDB server is running.

Is MongoDB ObjectId unique?

Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>).

Is MongoDB ObjectId incremental?

MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents.

What type is MongoDB ObjectId?

ObjectId is one data type that is part of the BSON Specification that MongoDB uses for data storage. It is a binary representation of JSON and includes other data types beyond those defined in JSON. It is a powerful data type that is incredibly useful as a unique identifier in MongoDB Documents.


1 Answers

The MongoLab UI uses Strict MongoDB Extended JSON so Object IDs are represented thusly, as in the second code block of the OP:

{ "$oid": "<id>" }
like image 163
jared Avatar answered Sep 28 '22 07:09

jared