我的网站上有一个表格,用户可以在其中的搜索字段中输入一个词,我希望 mongodb 在特定对象中搜索这些词并仅返回匹配的对象。搜索文本在请求查询中发送。
我使用以下代码进行分页,但缺少搜索功能。
const result = await orders.aggregate([
{ $facet: {
rows: [
{ $match: { status: {
$in: ['received', 'packing', 'packed', 'fulfilled', 'rejected', 'withdrawn'],
},
} },
{ $skip: offsetPage * parseInt(req.query.rowsPerPage) },
{ $limit: parseInt(req.query.rowsPerPage) },
{ $project: {
record: 1,
status: 1,
onPalette: 1,
note: 1,
grossTotal: 1,
receivedLog: 1,
arrivalDate: 1,
partner: 1,
location: 1,
} },
],
count: [
{ $count: 'count' },
],
} },
]).toArray();
我想在“记录”字段中搜索一个数字,并在合作伙伴的名称“partner.name”中搜索一个字符串。
如果没有发送搜索查询,或者搜索查询 (req.query.filter) 是空字符串,则返回所有内容
最佳答案
{ "_id" : 1, "location" : "24th Street",
"in_stock" : [ "apples", "oranges", "bananas" ] }
{ "_id" : 2, "location" : "36th Street",
"in_stock" : [ "bananas", "pears", "grapes" ] }
{ "_id" : 3, "location" : "82nd Street",
"in_stock" : [ "cantaloupes", "watermelons", "apples" ] }
db.fruit.aggregate([
{
$project: {
"store location" : "$location",
"has bananas" : {
$in: [ "bananas", "$in_stock" ]
}
}
}
])
OUTPUT --
{ "_id" : 1, "store location" : "24th Street", "has bananas" : true }
{ "_id" : 2, "store location" : "36th Street", "has bananas" : true }
{ "_id" : 3, "store location" : "82nd Street", "has bananas" : false }
关于javascript - 如何通过查询过滤器在mongodb中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54706073/