MongoDB按属性名称搜索具有该属性的任何文档

Rob*_*obV 7 mongodb

如何在MongoDB中搜索具有给定属性的任何文档?

我想要做的是找到所有具有该属性的文档,无论它的价值如何,我似乎无法做到这一点.我尝试了以下内容

db.collection.find({"property", null}); //Finds things that don't have that property
db.collection.find({"proprety", {}}); //Doesn't find anything unless something has the empty object as the value
Run Code Online (Sandbox Code Playgroud)

实际上有这种语法还是我需要进行mapreduce操作?

vla*_*mir 8

以下是使用$ exists的示例答案:

db.collection.find( { property : { $exists: true } } );
Run Code Online (Sandbox Code Playgroud)


hal*_*dan 7

只需反转查询并搜索属性不为null的文档($ ne not equals)

db.collection.find( { property : { $ne : null } } );
Run Code Online (Sandbox Code Playgroud)

  • 经过多次搜索后,看起来$ exists也可以完成同样的工作 (3认同)