首先让我们创建一个包含文档的集合-
>db.missingDocumentDemo.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3fb1eedc6604c74817ce6") } >db.missingDocumentDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3fb29edc6604c74817ce7") } >db.missingDocumentDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd3fb40edc6604c74817ce8") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.missingDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd3fb1eedc6604c74817ce6"), "StudentFirstName" : "Adam", "StudentLastName" : "Smith" } { "_id" : ObjectId("5cd3fb29edc6604c74817ce7"), "StudentFirstName" : "Carol", "StudentLastName" : "Taylor" } { "_id" : ObjectId("5cd3fb40edc6604c74817ce8"), "StudentFirstName" : "David", "StudentLastName" : "Miller", "StudentAge" : 21 }
这是仅在缺少MongoDB文档字段时才插入的查询。我们正在尝试在此处插入StudentAge字段。如果该字段已经存在,则不会插入该字段-
> db.missingDocumentDemo.update( ... { "StudentAge": { "$exists": false } }, ... { "$set": { "StudentAge": 23 } }, ... { "multi": true } ... ); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
让我们显示上述集合中的所有文档-
> db.missingDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd3fb1eedc6604c74817ce6"), "StudentFirstName" : "Adam", "StudentLastName" : "Smith", "StudentAge" : 23 } { "_id" : ObjectId("5cd3fb29edc6604c74817ce7"), "StudentFirstName" : "Carol", "StudentLastName" : "Taylor", "StudentAge" : 23 } { "_id" : ObjectId("5cd3fb40edc6604c74817ce8"), "StudentFirstName" : "David", "StudentLastName" : "Miller", "StudentAge" : 21 }