Use $addToSet to create a new field in MongoDB. Let us first create a collection with documents −
> db.createFieldDemo.insertOne({"StudentFirstName":"John","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99e28b50a6c6dd317ad95") } > db.createFieldDemo.insertOne({"StudentFirstName":"Larry","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99e2fb50a6c6dd317ad96") } > db.createFieldDemo.insertOne({"StudentFirstName":"Chris","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99e38b50a6c6dd317ad97") } > db.createFieldDemo.insertOne({"StudentFirstName":"David","StudentAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5cd99e43b50a6c6dd317ad98") }
Following is the query to display all documents from a collection with the help of find() method −
> db.createFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd99e28b50a6c6dd317ad95"), "StudentFirstName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cd99e2fb50a6c6dd317ad96"), "StudentFirstName" : "Larry", "StudentAge" : 23 } { "_id" : ObjectId("5cd99e38b50a6c6dd317ad97"), "StudentFirstName" : "Chris", "StudentAge" : 22 } { "_id" : ObjectId("5cd99e43b50a6c6dd317ad98"), "StudentFirstName" : "David", "StudentAge" : 25 }
Following is the query to create a new field. Here, we are creating a field “StudentLastName” −
> db.createFieldDemo.update({_id: ObjectId("5cd99e43b50a6c6dd317ad98")}, {$addToSet: {"StudentLastName": "Miller"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check all documents from the above collection −
> db.createFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd99e28b50a6c6dd317ad95"), "StudentFirstName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cd99e2fb50a6c6dd317ad96"), "StudentFirstName" : "Larry", "StudentAge" : 23 } { "_id" : ObjectId("5cd99e38b50a6c6dd317ad97"), "StudentFirstName" : "Chris", "StudentAge" : 22 } { "_id" : ObjectId("5cd99e43b50a6c6dd317ad98"), "StudentFirstName" : "David", "StudentAge" : 25, "StudentLastName" : [ "Miller" ] }