mongodb找到一份非常严格的文件

SRe*_*ane 2 find mongodb

我想返回一个非常严格的文档,它只包含一个特定的字段.

这里是情况:文件返回 db.test.find()

{"_id":ObjectId("562693f46fdf6dd2a0c97ad6"),"shape":"circle","color":"red","age": "20"}
{"_id":ObjectId("562694046fdf6dd2a0c97ad7"),"shape":"circle","color":"blue","age": "42"}
{"_id":ObjectId("562694306fdf6dd2a0c97ad8"),"shape":"circle","color":"green"}
{"_id":ObjectId("562694306fdf6dd2a0c97ad8"),"shape":"blabla","color":"blabla"}
Run Code Online (Sandbox Code Playgroud)

如何返回仅包含字段的文档:形状和颜色,并省略所有其他字段上包含更多其他字段的文档.所以结果应该是这样的:

{"_id":ObjectId("562694306fdf6dd2a0c97ad8"),"shape":"circle","color":"green"}
{"_id":ObjectId("562694306fdf6dd2a0c97ad8"),"shape":"blabla","color":"blabla"}
Run Code Online (Sandbox Code Playgroud)

编辑:所有其他字段都是未知的,因此使用age:{$ exists:false}}是不可能的

小智 5

一种方法是检查两个字段是否存在,并约束到具有正好3个字段(形状,颜色,_id)的结果:

db.test.find({
    shape: { $exists: true },
    color: { $exists: true },
    $where: function() { return Object.keys(this).length === 3 }  
})
Run Code Online (Sandbox Code Playgroud)

$where此答案还提到了使用的替代方法:基于记录中字段数量的Mongodb查询