我是node.js和mongodb的初学者,请原谅我,如果我的问题很愚蠢。基本上我要做的就是搜索字段的全名,这样工作正常,但如果我想搜索所有全名,除了一个全名,然后怎么做。
代码:
//This code is working fine
var string = data.search.replace(/[\/\\#@+()$~%'":*?<>{}]/g, '')
var regex = new RegExp(["^", string].join(""), "i");
db.collection("user_information").find({fullname:regex },{_id:0}).toArray(function(err, result) {
if(err) throw err;
console.log(result);
socket.emit("search",result)
db.close();
});
但此代码出错
db.collection("user_information").find({fullname:regex },
{fullname:{$ne:"david jones"}}).toArray(function(err, result) {
if(err) throw err;
console.log(result);
socket.emit("search",result)
db.close();
});//I'm trying to exclude the name by "$ne"
这是[]
db.collection("user_information").find({fullname:{regex,$ne:"srinivas.nahak"}}).toArray(function(err, result) {
if(err) throw err;
console.log(result);
socket.emit("search",result)
db.close();
});
错误:
MongoError: Unsupported projection option: fullname: { $ne: "srinivas.nahak" }
at Function.MongoError.create (C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\node_modules\mongodb-core\lib\cursor.js:212:36)
at C:\Users\Srinu\AppData\Roaming\npm\node_modules\mongodb\node_modules\mongodb-core\lib\connection\pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
答案 0 :(得分:2)
我很确定你的论证中需要另一个分号才能找到。 E.g。
{fullname:{$ ne:&#34; david jones&#34; }}
请参阅此处的官方文档
https://docs.mongodb.com/manual/reference/operator/query/ne/
虽然在官方文档的第二次阅读中,$ ne可能不是投影中的有效运算符 - 您可能必须在实际查询中包含它。
我相信find的第二个参数允许你指定应该从查询中返回的字段I.e.
{field1:1,field2:0}
这将确保返回field1但不包括field2。
看起来您可以在投影中传递的值可以是1,true,0,false,$,$ elemMatch,$ slice,$ meta
https://docs.mongodb.com/manual/reference/operator/projection/#
您可以使用$和 - 结帐文档在此处构建所需的查询:
https://docs.mongodb.com/manual/reference/operator/query/and/