If I create an index for username field, which document is better for query a specific user?
The nested one:
{ account:{ username:'zhengyi', passwd:'zhengyi', friends:[] } dev:{ os:'iOS', ver:'6.0', hw:'iPhone2,1' }, app:{ ver:'1.0', pver:'1.0' } }
The unnested one:
{ username:'zhengyi', passwd:'zhengyi', friends:[], dev:{ os:'iOS', ver:'6.0', hw:'iPhone2,1' }, app:{ ver:'1.0', pver:'1.0' } }
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
You can retrieve these nested documents by using db. collection. find() method in mongosh. This document has a field name “item” that contains another document, and this document contains two fields with values (that is, sku, color).
An embedded, or nested, MongoDB Document is a normal document that's nested inside another document within a MongoDB collection. Embedded documents are particularly useful when a one-to-many relationship exists between documents.
It doesn't make a difference
You're either doing:
db.collection.findOne({"username":"zhengyi"});
or
db.collection.findOne({"account.username":"zhengyi"});
Read up on the dot notation for embedded documents
Similarly, indexes use the dot notation to reach inside a document:
db.collection.ensureIndex({"username": 1});
Or
db.collection.ensureIndex({"account.username": 1});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With