Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance difference for nested document in mongodb query

Tags:

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'         }     } 
like image 202
user1826237 Avatar asked Nov 15 '12 10:11

user1826237


People also ask

How do I query a nested document in MongoDB?

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.

How does MongoDB calculate nested value?

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).

When should we embed one document within another in MongoDB?

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.


1 Answers

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}); 
like image 102
Alex Avatar answered Oct 22 '22 09:10

Alex