如何在MongoDB中多次使用同一字段在NodeJS中查找查询 [英] How to use same field multiple times in MongoDB find query in NodeJS
问题描述
我有一个MongoDB集合,记录中有一个"name"
字段,我试图执行一个查找查询,其中名称字段在查询中出现两次.我想通过$nin
排除某些名称,并对其他名称执行正则表达式搜索.它似乎无法正常工作,因为它返回了所有记录.如果我只进行了正则表达式搜索或$nin
搜索,则可以按预期运行.
I have a MongoDB collection with records having a "name"
field, I am trying to perform a find query where the name field appears twice in the query. I want to exclude certain names, via $nin
, and perform regex search for other names. It doesn't seem to be working, as it returns all records. If I just have the regex search or the $nin
search, it works as expected.
db.users.find({name:{$nin:[current_user]}).cb(array)
-有效
db.users.find({name:new RegExp(/query/)}).cb(array)
-有效
db.users.find({name:{$nin:[current_user]}, name:new RegExp(/query/)}).cb(array)
-不起作用,current_user不会从查找结果中排除.
db.users.find({name:{$nin:[current_user]}, name:new RegExp(/query/)}).cb(array)
- does NOT work, the current_user is NOT excluded from the find result.
我有一种感觉,find命令对同一字段的多次出现进行最后一次查询,是这样吗?而我该如何解决呢?
I have a feeling, the find command takes the last query for multiple occurrences of the same field, is that so? And how do I get around it?
感谢您的帮助, 加里
推荐答案
您的查询JSON对象包含两次name
字段,这使查询中断.请注意 $and
mongo查询运算符.有两种方法可以构造正确的查询:
Your query JSON object contains name
field two times, and it breaks the query. Pay attention to the $and
mongo query operator. There are two ways to construct correct query:
1) db.users.find({ $and: [{ name: { $nin: [current_user] } }, { name: { $regex: new RegExp(/query/) } }] })
2) db.users.find({ name: { $nin: [current_user], $regex: new RegExp(/query/) } })
此外,如果您仅排除一个用户,则可以使用 $ne
运算符,而不是$nin
.
Also, if you exclude only one user, you can use $ne
operator instead of $nin
.
这篇关于如何在MongoDB中多次使用同一字段在NodeJS中查找查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!