'Can I add two different fields with same names inside a document? This may not be the Logical question but I just want to know if it is possible

I tried below code but it is only inserting first field which is name :"Swapnil"

db.emp.insert ({name:"Swapnil", name:"Aditya"}) 


Solution 1:[1]

The The JavaScript Object Notation (JSON) Data Interchange Format specification actually would permit it:

When the names within an object are not unique, the behavior of software that receives such an object is unpredictable. Many implementations report the last name/value pair only. Other implementations report an error or fail to parse the object, and some implementations report all of the name/value pairs, including duplicates.

The MongoDB documentation - Field Names says:

BSON documents may have more than one field with the same name. Most MongoDB interfaces, however, represent MongoDB with a structure (e.g. a hash table) that does not support duplicate field names. If you need to manipulate documents that have more than one field with the same name, see the driver documentation for your driver.

Short answer: it depends on the driver/application you use, it could be possible - but clearly it is not recommended

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 Wernfried Domscheit