Unlike SQLite, which requires a separate virtual table for text search, MongoDB enables us to create a text index on the fields of a regular collection.
db.knowledgebase.createIndex({
title: "text",
body: "text"
});
// Alternatively, a wild-card text index can be created with:
// db.knowledgebase.createIndex({"$**": "text"});
db.knowledgebase.insertOne({
title: "How to setup DNS",
body: "Create AAAA and PTR records"
});
db.knowledgebase.find({
"$text": {"$search": "DNS"}
}, {
score: {"$meta": "textScore"}
}).sort({score: {"$meta": "textScore"}});
MongoDB provides the ability to search for exact strings (by enclosing within escaped quotations). Although the find operation cannot target specific fields of the document for the text search, weights can be assigned to the fields when creating the text index.
db.blogPosts.createIndex({
title: "text",
body: "text"
}, {
weights: {
title: 2,
body: 1 // 1 is the default weight
}
});