【问题标题】:how to select all documents from mongodb where one field does not equal a certain value如何从mongodb中选择一个字段不等于某个值的所有文档
【发布时间】:2015-01-29 02:05:40
【问题描述】:

我希望从名为 Posts 的 mongodb 表中选择字段“作者”不等于某个用户名的所有文档。

到目前为止我尝试过

Posts.find( { author: { $not: 'username' } } );

这不起作用,它返回了所有内容

有什么想法吗?

【问题讨论】:

  • 如果我在控制台Posts.find( { author: { $not: "molleman" } } ).fetch(); 上运行它会返回[],这不是你想要的吗? ... Posts.find( { author: { $not: "molleman"} } ).count(); 返回 0 和 Posts.find().count(); 返回 42
  • $not 运算符不接受字符串作为输入。
  • 我只是在控制台上运行它,为了显示它有效,它应该是输入值的问题,也许是molleman它没有传递正确的值或什么

标签: javascript node.js mongodb meteor database


【解决方案1】:

如果输入是字符串,请使用$ne 运算符。

Posts.find( { author: { $ne: 'username' } } );

$not 运算符将expressionregex 作为输入,并在表达式的情况下对输出执行逻辑非。

$not 对指定的对象执行逻辑 NOT 操作 <operator-expression> 并选择不匹配的文档 <operator-expression>。这包括不包含 字段。

Syntax: { field: { $not: { <operator-expression> } } }

您可以通过这种方式将regex 传递给$not 运算符:

var reg = new RegExp('username');
Posts.find( { author: { $not: reg } } );

【讨论】:

  • 刚刚也试过了,不工作,如果需要,请查看themmatrends.com,您可以在浏览器控制台中进行测试....
  • @molleman - 您能否使用集合中的示例文档更新您的问题并传递正确的输入。您的代码中可能还缺少其他内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2017-09-21
相关资源
最近更新 更多