Rohanil
Rohanil

Reputation: 1887

$and operator on multiple $text search in mongo

Is it possible to have $and operator on multiple $text index search in mongo?

I have documents in tp collection of my db

> db.tp.find()
{ "_id" : ObjectId("...."), "name" : "tp", "dict" : { "item1" : "random", "item2" : "some" } }
{ "_id" : ObjectId("...."), "name" : "tp", "dict" : { "item3" : "rom", "item4" : "tttt" } }

Then I do

> db.tp.createIndex({ "$**": "text" })
> db.tp.find({ $and: [{$text : { $search: "random" } }, {$text : { $search: "redruth" } }]})

And it fails with

Error: error: {
"waitedMS" : NumberLong(0),
"ok" : 0,
"errmsg" : "Too many text expressions",
"code" : 2
}

but text index search works for single search so is it not possible to bind multiple text searches with $and operator? By the way I am using wildcard character $** for indexing because I want to search over entire document.

Upvotes: 4

Views: 4553

Answers (2)

Daniele Graziani
Daniele Graziani

Reputation: 496

A query can specify at most one $text expression. See:

https://docs.mongodb.com/manual/reference/operator/query/text/

Upvotes: 2

ikandars
ikandars

Reputation: 526

Base on mongoDB docs, AND operator can use directly in search term by combining quote and space. For example, we search for "ssl certificate" AND "authority key", so the query should like:

> db.tp.find({'$text': {'$search': '"ssl certificate" "authority key"'}})

Upvotes: 7

Related Questions