【问题标题】:How to get negation of a MongoDB query?如何否定 MongoDB 查询?
【发布时间】:2013-02-06 21:27:52
【问题描述】:

我的查询是:

db.users.find({"username" : {$regex : ".*substring.*"}});

我需要不包含“子字符串”的用户名,而不是获取包含它的用户名。

【问题讨论】:

  • 你试过$not操作符吗?
  • $not 效果很好,谢谢!

标签: mongodb


【解决方案1】:

为此,您可以使用 $not 运算符:

db.test.find( { username: { $not: /substring/ } } );

喜欢:

> db.test.insert( { username: "Derick Rethans" } );
> db.test.insert( { username: "Hannes Magunusson" } );
> db.test.find( { username: { $not: /ag/ } } );
{ "_id" : ObjectId("511258b36879ad400c26084f"), "username" : "Derick Rethans" }

但是,您需要注意正则表达式$not 运算符的使用会阻止索引的使用。如果您需要经常执行此查询,您可能需要仔细查看您的架构设计。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-15
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2019-03-27
    • 1970-01-01
    相关资源
    最近更新 更多