'Query using ObjectId in MongoDB

I have a notes collection as:

{
    note: {
            type: String,
    },
    createdBy: {
        type: String,
        required: true
    },
}

where "createdBy" contains _id of a user from users collection. First Question: Should I define it as String or ObjectId?

Second Question: While querying the data as db.users.find({ createdBy: ObjectId(userid) },'notes'). Is it a O(1) operation? Or, do I have to create an index for that to be 0(1)?



Solution 1:[1]

  1. If your user collection is using ObjectId then you would better also use ObjectId in notes collection since you may want to $lookup them.

  2. Only _id field would create index in the begging of collection. You need to create index for createdBy since you want O(1) operation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YuTing