Hi @Shah_Kushal,
Welcome to the MongoDB community!
As is, this wouldn’t be a valid shard key. Trying to shard a collection with this would result in an error.
For example, using MongoDB 4.2:
“Shard key { Username: “Kushal” } can contain either a single ‘hashed’ field or multiple numerical fields set to a value of 1. Failed to parse field Username”
However, assuming you sharded on Username: 1
, lets see what happens when a document is inserted without the shard key:
mongos> db.users.insert({ID : 3})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 61,
"errmsg" : "document { _id: ObjectId('5eb2713cf49a3bda89da595c'), ID: 3.0 } does not contain shard key for pattern { Username: 1.0 }"
}
})
Every document inserted into a sharded collection must contain the shard key. A document will be associated with a single shard based on the shard key index.
Queries based on the shard key (or a prefix of a compound shard key) will only target the relevant shards. Queries on a sharded collection that don’t fit that criteria will be broadcast to all shards. For more information, see Targeted Operations vs Broadcast Operations in the MongoDB documentation.
To learn more about MongoDB I would recommend taking the free online courses at MongoDB University and following one of the learning paths (DBA or Developer).
Regards,
Stennie