How to create compound index of text fields and numeric fields

Hi,

Just as and example, say I have Collection of following items:

{
   description: some descripton here
   name: John Galt
   status: 1
}

I would like to have text index for name and description and I want to be able to find all documents, where status equals to 1.

I create index this way:

db.collection.createIndex({“name”:“text”, 'description":“text”, “status”:1});

but I don’t get how to query the document above: say I want to search by:

$text: John
and “status”:1

I’m new to MongoDB, just 2nd day looking into it so appreciate help from community.

Thanks

Hello @T_W, welcome to the community.

You can do your search as follows using the compound text index you had created:

db.collection.find( { status: 1, $text: { $search: "John" } } )

-or-

db.collection.find( { $text: { $search: "John" }, status: 1 } )

The result with both the queries is the same. That is the order of the fields in the query doesn’t matter. But, the order of the fields used with creating index matters how the index is used.