'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]
If your user collection is using
ObjectIdthen you would better also useObjectIdin notes collection since you may want to$lookupthem.Only
_idfield would create index in the begging of collection. You need to create index forcreatedBysince 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 |
