Reputation: 39
I have a table on my website where users can type in a word in a search field, and I want mongodb to search for those words in specific objects and return only matching objects. The search text is sent in the request query.
I use the following code for pagination, but the search feature is missing.
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();
I would like to search in the "record" field which is a number, and in a partner's name "partner.name" which is a string.
If no search query sent, or the search query (req.query.filter) is an empty string just return everything
Upvotes: 1
Views: 37
Reputation: 89
{ "_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 }
Upvotes: 1