如果您想在找不到文档时插入一个文档,可以在update()
方法中使用upsert
选项:
collection.update(_query_, _update_, { upsert: true });
查看关于 upsert 行为的文档。
使用 $exists
运算符的示例。
假设您的集合中有 6 个文档:
> db.test.find()
{ "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 }
{ "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] }
{ "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] }
{ "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] }
{ "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }
{ "_id": ObjectId("5495af60f83774152e9ea6b9"), "b": 2 }
如果您想查找具有特定字段"a"
的文档,您可以使用find()
方法与$exists运算符(node文档)。注意:这也会返回字段为空数组的文档。
> db.test.find( { a: { $exists: true } } )
{ "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 }
{ "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] }
{ "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] }
{ "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] }
{ "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }
{ "instruments" : { $exists : true } }
,而_document_是你想要更新的内容,例如使用$set
来设置某个值或者使用$push
来向数组中追加元素。 - Gianfranco P.