Phineas
Phineas

Reputation: 35

Are MongoDB document IDs unique to the entire database or just that collection?

I'm using MLab to host a MongoDB database for a node.js project I'm working on. I want to use the uids automatically given to document to identify specific documents across collections. I was wondering if the default ids are unique only in the collection the document is in, or if they are unique throughout the entire database.

{
    "_id": { // <<<< this is what I'm talking about
        "$oid": "5c0754d8d0d1c81b400690a3"
    },
    "owned": [],
    "equipped": [],
    "prospects": [],
    "username": "Urist",
    "password": "dcddb75469b4b4875094e14561e573d8",
    "date": {
        "$date": "2018-12-05T04:32:24.690Z"
    },
    "trades": [],
    "__v": 0
}

Upvotes: 0

Views: 610

Answers (1)

kevinadi
kevinadi

Reputation: 13785

_id must be unique across a single collection. It is not necessary for _id to be unique for documents in different collection or database.

In https://docs.mongodb.com/manual/core/document/#field-names:

The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.

Upvotes: 1

Related Questions