如果您想插入一个未找到的文档,您可以使用upsert
选项中的update()
method:
collection.update(_query_, _update_, { upsert: true });
请参阅文档upsert https://docs.mongodb.com/manual/reference/method/db.collection.update/#upsert-behavior行为。
一个例子$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 http://docs.mongodb.org/manual/reference/operator/query/exists/操作员 (节点文档 http://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html?highlight=exists#special-query-operators)。注意:这还将返回字段为空数组的文档。
> 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 ] }