[英]How to search specific documents by excluding some fields in mongodb?
我是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)
我很確定您的論點中需要找到另一個分號。 例如
{全名:{$ ne:“大衛瓊斯”}}
在這里查看$ ne的官方文檔
https://docs.mongodb.com/manual/reference/operator/query/ne/
盡管對官方文檔進行了二讀,但$ ne可能不是投影中的有效運算符-您可能必須在實際查詢中包括此內容。
我相信要查找的第二個參數允許您指定應從查詢中返回的字段,即
{field1:1,field2:0}
這將確保返回field1,但排除field2。
看起來您可以在投影中傳遞的值可以是1,true,0,false,$,$ elemMatch,$ slice,$ meta
https://docs.mongodb.com/manual/reference/operator/projection/#
您可以使用$ and-結帳文檔來建立所需的查詢:
https://docs.mongodb.com/manual/reference/operator/query/and/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.