Home > Mobile >  MongoDB: Searching objects that contain a specific keyword
MongoDB: Searching objects that contain a specific keyword

Time:02-17

This is one example of the object in my collection:

{ title : "Picture 1" ,
  user  : "John",
  information : [ { "App" : "Google Chrome", "time" : Monday},
                  { "App" : "Safari", "time" : Tuesday}]
}

I want to search a specific keyword in many objects, for example, "John".

Currently, I can search a keyword in "title" and "user" fields. Below is my code:

db.collection(Nmae).createIndex({title:"text",users:"text"});
result = db.collection(Name).find({$text:{$search: "John"}});

However, I don't know how to search this same keyword in the "information" field. Searching a word in an array seems different from searching in strings. If my keyword is "Google" and treats "information" as another "text", these lines of code don't work.

Can somebody help me with this out? Thank you so much!

CodePudding user response:

To do a text search in your array of documents, you will need to create a multikey index.

db.collection(name).createIndex({title:"text",users:"text","information.App":"text"})

Official Documentation that could assist you:

  1. text search
  2. multikey
  3. Example of the multikey index with text indexes
  • Related