MongoDB字段选择包括没有字段的文档

时间:2012-11-25 12:36:23

标签: mongodb mongodb-query

假设我有一个包含两个文件的集合......

{"_id": ..., "msg": "hello world"}
{"_id": ..., "name": "bob dylan"}

和查询...

db.collection.find({}, {"text": 1})

为什么这会返回两个文件?有没有办法只在msg字段存在时返回?

1 个答案:

答案 0 :(得分:3)

您的查询会返回两个文档,因为您的条件为空({}):

db.collection.find({}, {"text": 1})

如果您只想查找存在msg字段的文档,可以使用$exists

db.collection.find({ msg: { $exists: true}}, { "text" : 1 })

请注意,对于find()的第二个参数,您只需要显示text字段的值。

相关问题