Skip to content

Instantly share code, notes, and snippets.

@NguyenTungs
Last active December 22, 2017 07:58
Show Gist options
  • Save NguyenTungs/79a140676df806fd73e43c43adb4fb8a to your computer and use it in GitHub Desktop.
Save NguyenTungs/79a140676df806fd73e43c43adb4fb8a to your computer and use it in GitHub Desktop.
db.messages.insert({"subject":"Joe owns a dog", "content":"Dogs are man's best friend", "likes": 60, "year":2015, "language":"english"})
db.messages.insert({"subject":"Dogs eat cats and dog eats pigeons too", "content":"Cats are not evil", "likes": 30, "year":2015, "language":"english"})
db.messages.insert({"subject":"Cats eat rats", "content":"Rats do not cook food", "likes": 55, "year":2014, "language":"english"})
db.messages.insert({"subject":"Rats eat Joe", "content":"Joe ate a rat", "likes": 75, "year":2014, "language":"english"})
## Creating a Text Index
db.messages.createIndex({"subject":"text"})
db.messages.find({$text: {$search: "dogs"}}, {score: {$meta: "toextScore"}}).sort({score:{$meta:"textScore"}})
{ "_id" : ObjectId("55f4a5d9b592880356441e94"), "subject" : "Dogs eat cats and dog eats pigeons too", "content" : "Cats are not evil", "likes" : 30, "year" : 2015, "language" : "english", "score" : 1 }
{ "_id" : ObjectId("55f4a5d9b592880356441e93"), "subject" : "Joe owns a dog", "content" : "Dogs are man's best friend", "likes" : 60, "year" : 2015, "language" : "english", "score" : 0.6666666666666666 }
## dexing Multiple Fields (Compound Indexing)
db.messages.createIndex({"subject":"text","content":"text"})
or we can drop index, if u want
db.messages.dropIndex("subject_text")
db.messages.createIndex({"subject":"text","content":"text"})
db.messages.find({$text: {$search: "cat"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})
### result
{ "_id" : ObjectId("55f4af22b592880356441ea4"), "subject" : "Dogs eat cats and dog eats pigeons too", "content" : "Cats are not evil", "likes" : 30, "year" : 2015, "language" : "english", "score" : 1.3333333333333335 }
{ "_id" : ObjectId("55f4af22b592880356441ea5"), "subject" : "Cats eat rats", "content" : "Rats do not cook food", "likes" : 55, "year" : 2014, "language" : "english", "score" : 0.6666666666666666 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment