使用$addToSet在MongoDB中创建一个新字段。首先让我们创建一个包含文档的集合-
> 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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.createFieldDemo.find().pretty();
这将产生以下输出-
{ "_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”-
> db.createFieldDemo.update({_id: ObjectId("5cd99e43b50a6c6dd317ad98")}, {$addToSet: {"StudentLastName": "Miller"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查上述集合中的所有文档-
> db.createFieldDemo.find().pretty();
这将产生以下输出-
{ "_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" ] }