Question

I need to find all document values which are within a text/string:

Example:

Imagine I have the tag collection with the following documents:

db.tag.find()
{ "_id" : ObjectId("536f7107c55b2acc61000bc8"), "name" : "star" }
{ "_id" : ObjectId("536f710fc55b2acc61000bc9"), "name" : "star wars" }
{ "_id" : ObjectId("536f7117c55b2acc61000bca"), "name" : "spider" }
{ "_id" : ObjectId("537087d16ac5b5f6f58f0b1b"), "name" : "starting" }

I need something like this (example in mongodb shell):

db.tag.find({"name": { $subStrOF: "star wars episode VII" }})

returning this:

{ "_id" : ObjectId("536f7107c55b2acc61000bc8"), "name" : "star" }
{ "_id" : ObjectId("536f710fc55b2acc61000bc9"), "name" : "star wars" }

Any idea?

Thank you very much

Was it helpful?

Solution 2

I got it working using $where, example below:

Command:

db.tag.find({$where:"'star wars episode VII'.search("star") >= 0"})

The output:

{ "_id" : ObjectId("536f7107c55b2acc61000bc8"), "name" : "star" }
{ "_id" : ObjectId("536f710fc55b2acc61000bc9"), "name" : "star wars" }

Hope it helps

OTHER TIPS

Firstly, Start the mongod process with command line options

--setParameter textSearchEnabled=true

Example:

mongod --setParameter textSearchEnabled=true

Then in your mongo shell, create an index for name in tag collection

db.tag.ensureIndex({name : "text"});

Now you can query using text:

db.tag.runCommand("text", {search : "star wars episode"});

This will return you something like this

{
        "queryDebugString" : "star||||||",
        "language" : "english",
        "results" : [
                {
                        "score" : 1.1,
                        "obj" : {
                                "_id" : ObjectId("536f7107c55b2acc61000bc8"),
                                "name" : "star"
                        }
                },
                {
                        "score" : 0.75,
                        "obj" : {
                                "_id" : ObjectId("536f710fc55b2acc61000bc9"),
                                "name" : "star wars"
                        }
                }
        ],
        "stats" : {
                "nscanned" : 2,
                "nscannedObjects" : 0,
                "n" : 2,
                "nfound" : 2,
                "timeMicros" : 152
        },
        "ok" : 1
}

To get only the results:

db.tag.runCommand("text", {search : "star wars episode"}).results

I have tested it with my local DB and it works fine. please check it

For more info about text : Mongo DOCs

BTW from mongoDB 2.6: DOCS

db.tag.find({$text : {$search : "star wars episode VII"}});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top