我在MongoDB中有一个集合,名为userRegister,它有name,age,mobileno,email,... activityViewed等字段。其中userid是主键,由MongoDB自动生成。我如何在nodejs中搜索这20个字段?我在MongoDB上试过索引,但它不起作用,它只是给予我一列搜索.(作为索引)
userRegister
name
age
mobileno
email
activityViewed
userid
m1m5dgzv1#
如果要执行基于文本的搜索,可以将$or运算符与正则表达式或文本搜索结合使用。
$or
const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const dbName = 'your_database_name'; const client = new MongoClient(url); client.connect(function(err) { console.log('Connected successfully to server'); const db = client.db(dbName); const collection = db.collection('userRegister'); // Create an index on the fields you want to search collection.createIndex({ name: 'text', age: 'text', mobileno: 'text', email: 'text' }); // Define your search query const query = { $or: [ { name: { $regex: 'search_term', $options: 'i' } }, // Case-insensitive regex search for name { age: { $regex: 'search_term', $options: 'i' } }, // Case-insensitive regex search for age { mobileno: { $regex: 'search_term', $options: 'i' } }, // Case-insensitive regex search for mobileno { email: { $regex: 'search_term', $options: 'i' } }, // Case-insensitive regex search for email // ... ] }; collection.find(query).toArray(function(err, docs) { console.log('Found the following records:'); console.log(docs); }); client.close(); });
字符串
1条答案
按热度按时间m1m5dgzv1#
如果要执行基于文本的搜索,可以将
$or
运算符与正则表达式或文本搜索结合使用。字符串