I have a basic collection of users that have their firstName
, lastName
and a few other details.
How would I simply search for users by a combination of both names, or partial search?
For example, for a collection of:
{
firstName: Bob,
lastName: Jerry
}, {
firstName: Clark,
lastName: Mcbobby
}
If the search term was bob
, both users would be returned since the first documents firstName
is bob, and the last users lastName
contains bob
. If bob j
was the search term, just the first document would be returned since if both names are combine, it equals Bob Jerry
which matches the search term.
I tried creating a basic aggregate
to concatenate the names and then make a match, although Mongoose kept throwing me an error of: Arguments must be aggregate pipeline operators
.
Here is my current code:
User.aggregate({
$project: { "name" : { $concat : [ "$firstName", " ", "$lastName" ] } },
$match: {"name": {$regex: "/bob j/i"}}
}).exec(function(err, results) {
...
});
Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.
You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .)
I see couple of mistakes in your code causing undesired result.
Aggregation pipeline accepts array of aggregation framework operations. In your case, you are missing []
operator. It should be like
User.aggregate([{$project...},{$match...}])
In $match stage you are using regex, if you are using /../
style of regex, you don't need to wrap it around string quotes. It should be /bob j/i
Here is finished example:
User.aggregate([
{$project: { "name" : { $concat : [ "$firstName", " ", "$lastName" ] } }},
{$match: {"name": {$regex: /bob j/i}}}
]).exec(function(err, result){
console.log(result);
});
You should see [ { _id: 574c3e20be214bd4078a9149, name: 'Bob Jerry' } ]
on screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With