How to seach all value nearly exact in mongoose

mongoose aggregate
mongoose search all fields
mongoose text search multiple fields
search element in array mongoose
mongoose regex
mongoose find array contains
mongoose find value inside array
mongoose query array contains value

When I use userInfos.find({username:"John ABC"}) I need to get all people with "John" or ABC occurence.

Here is my code :

const userSchema = new mongoose.Schema({
    username:String,
    password:String,
});

const userInfos = mongoose.model('userInfos', userSchema);

What is the best way to do this

You can use the text search feature of the MongoDB.

$text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

First you need to create a text index for username field like this:

db.users.createIndex( { username: "text" } )

Then you can use the following code to search with mongoose:

const express = require("express");
const router = express.Router();
const User = require("../models/user");

router.get("/search", async (req, res) => {
  const result = await User.find({ $text: { $search: "John ABC" } }).select(
    "username"
  );

  res.send(result);
});

Let's say we have 5 users like this:

[
  {
    "_id": "ObjectId(\"5dea9bf903d65c440c1f169e\")",
    "username": "Jonas"
  },

  {
    "_id": ObjectId("5dea9bee03d65c440c1f169d"),
    "username": "ABCD"
  },
  {
    "_id": ObjectId("5dea9be103d65c440c1f169c"),
    "username": "John ABC"
  },

  {
    "_id": ObjectId("5dea9bd503d65c440c1f169b"),
    "username": "ABC",
  },

  {
    "_id": ObjectId("5dea9bcd03d65c440c1f169a"),
    "username": "John"
  }
]

Search will return these 3 users:

[
    {
        "_id": "5dea9bd503d65c440c1f169b",
        "username": "ABC"
    },
    {
        "_id": "5dea9be103d65c440c1f169c",
        "username": "John ABC"
    },
    {
        "_id": "5dea9bcd03d65c440c1f169a",
        "username": "John"
    }
]

This shows clearly that the search worked clearly.

You can even add text score and sort by score if you want like this:

router.get("/search", async (req, res) => {
  const result = await User.find(
    { $text: { $search: "John ABC" } },
    { score: { $meta: "textScore" } }
  )
    .sort({ score: { $meta: "textScore" } })
    .select("username");

  res.send(result);
});

The result will have score like this:

[
    {
        "_id": "5dea9be103d65c440c1f169c",
        "username": "John ABC",
        "score": 1.5
    },
    {
        "_id": "5dea9bcd03d65c440c1f169a",
        "username": "John",
        "score": 1.1
    },
    {
        "_id": "5dea9bd503d65c440c1f169b",
        "username": "ABC",
        "score": 1.1
    }
]

As you see, we have score field in the output, and users are sorted by score which is very useful.

If you use local MongoDB and if you have difficulty creating the text index, you can use mongo shell.

  1. Open a command in the bin folder you installed MongoDB server. For example C:\Program Files\MongoDB\Server\4.0\bin
  2. type mongo
  3. type db
  4. Using your db name, let's say it is auth, type use auth
  5. type db.users.createIndex( { username: "text" } )

And if you use MongoDB Atlas, you can create the text index like this:

  1. Connect to the MongoDB atlas
  2. Select your database, and collection
  3. In the Indexes tab, click CREATE INDEX button
  4. Create you index like this:

How to get all the values that contains part of a string using , You almost answered this yourself in your tags. MongoDB has a $regex operator which allows a regular expression to be submitted as a query. A mongoose query can be executed in one of two ways. First, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback . A query also has a .then() function, and thus can be used as a promise.

The MongoDB $or query is probably what you are looking for.

MongoDB and Mongoose, Use Model.find() Find all the people having a given name, using Model.find() -> [ Person] In MongoDB and Mongoose - Use model.find() to Search Your Database I've used the same exact code but it didn't work anyway. Serial numbers on Mongoose BMX bikes. If you find a Mongoose Decade for sale, a Mongoose FS1 for sale, or another vintage Mongoose BMX for sale, then you can tell when employees made the bike from the serial number. Old Mongoose bikes built in 1975 and early 1976 have a five-digit-stamped number.

you can filter the search using regex in your query.

userInfos.find({username:/(John|ABC)/g})

first the regex capture the group passed and check for first alternative which is 'John' here and then check for 'ABC'. don't forget the g flag which checks globally. you can use i flag for case insensitive which is much appreciated when user searches something.

Mongoose v5.9.26: Mongoose Tutorials: Working With Dates, When you create a user document, Mongoose will cast the value to a native Find episodes that aired on this exact date return Episode.find({ airedAt: new� Mongoose, any of nearly three dozen species of small bold predatory carnivores found mainly in Africa but also in southern Asia and southern Europe. Mongooses are noted for their audacious attacks on highly venomous snakes such as king cobras.

I suggest you read more carefully SuleymanSah's answer. Text search is likely to be interesting, tokenization wise, accent wise, ...

But to "minimally" answer your question:

A useful practice is to use your mongo shell, test your queries, and when satisfying, use them for mongoose

Consider the minimal dataset:

[ "Johhn", "Johhn Doe", "John Doef", " Doef John", "John - Doe", "lol" ].forEach(x=>db.dum.insert({ username: x }))
db.dum.find()
> db.dum.find()
{ "_id" : ObjectId("5deb4706b687c1e90e674099"), "username" : "Johhn" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409a"), "username" : "Johhn Doe" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409b"), "username" : "John Doef" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409c"), "username" : " Doef John" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409d"), "username" : "John - Doe" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409e"), "username" : "lol" }

With an $in predicate

Basically, username must match one of the provided regexs

var str = 'doe john'
var lowerCase = 'i'
var choices = str.split(/[^\w]+/).map(w => new RegExp(w, lowerCase))
db.dum.find({ username: { $in: choices } })
{ "_id" : ObjectId("5deb4706b687c1e90e67409a"), "username" : "Johhn Doe" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409b"), "username" : "John Doef" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409c"), "username" : " Doef John" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409d"), "username" : "John - Doe" }
With an $or predicate

Basically one of the or predicates must return true, predicate here being {username:someRegExp}

var str = 'doe john'
var orPred = str.split(/[^\w]+/).map(w => ({ username: new RegExp(w, 'i') }))
db.dum.find({ $or: orPred })

{ "_id" : ObjectId("5deb4706b687c1e90e67409a"), "username" : "Johhn Doe" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409b"), "username" : "John Doef" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409c"), "username" : " Doef John" }
{ "_id" : ObjectId("5deb4706b687c1e90e67409d"), "username" : "John - Doe" }

Understanding Mongoose Deep Population, It's almost like a “join” in a SQL language, but not quite (remember, Mongoose collects all of the _id fields that it needs to look for per� Browse other questions tagged javascript node.js mongodb mongoose or ask your own question. The Overflow Blog The Overflow #31: Fresh data

Text Search — MongoDB Manual, For example, you could use the following query to find all stores containing any You can also search for exact phrases by wrapping them in double-quotes. Meet the real predator behind the fictional Rikki-tikki-tavi. Hear the tales of mongoose populations under pressure, and others that have threatened to wipe out native species.

MongoDB Query operator: $all, The $all operator selects the documents where the value of a field is an array that contains all the specified elements. To specify an $all expression, use the� From Downhill Full Suspension bike to Dirt Jumper, from XC Hardtail to Fat Bike, Mongoose offers Mountain bikes for several MTB disciplines. Whether you're pushing through the most technical terrain or hitting the local trails as a family, Mongoose has the mountain bike for you.

Learn Mongoose find() by Example, MongoDB will search for all documents that match the filter . If you set the value of rank to an object with a $eq property, you get an equivalent query, but using a query The $eq query operator checks exact equality. Follow Mongoose @MONGOOSEBIKES @MONGOOSESCOOTERS. Sign Me Up. Get special offers, exclusive product news, and event info straight to your inbox.

Comments
  • should "doe john" be matched ?
  • yes it should be
  • wow thanks for awnser but i looking for way to do with mongoose
  • @luongvy this is mongoose, you see I query with mongoose model
  • if i have a string like const string = "John ABC"; how can i include this in to /()/g ?
  • the idea is to use the RegExp(str) constructor
  • yeah, you can use RegExp() construtor.. in your case, let str = "John ABC"; let res = str.split(" "); then userInfos.find({username: new RegExp(`(${res[0]}|${res[1]})`, "ig")}); Try this out.
  • observe that when you have multiple variables, you should pass variables within parenthesis and separate them using '|' and pass them inside template literal (`). second argument of RegExp is flags.