仅在 MongoDB 文档字段不存在时插入?
我们首先通过文档创建一个集合 -
>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 }
广告