3

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.

Rohanil
  • 1,717
  • 5
  • 22
  • 47

2 Answers2

7

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"'}})
ikandars
  • 486
  • 5
  • 5
2

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

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

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Daniele Graziani
  • 490
  • 4
  • 10