在多个字段中搜索MongoDB中的多个值?
要在MongoDB中的多个字段中搜索多个值,可以使用$text和$search运算符。首先让我们创建一个包含文档的集合
>db.searchMultipleFieldsDemo.insertOne({"_id":100,"FirstSubject":"Java","SecondSubject":"MongoDB"}); { "acknowledged" : true, "insertedId" : 100 } >db.searchMultipleFieldsDemo.insertOne({"_id":101,"FirstSubject":"MongoDB","SecondSubject":"MySQL"}); { "acknowledged" : true, "insertedId" : 101 } >db.searchMultipleFieldsDemo.insertOne({"_id":102,"FirstSubject":"MySQL","SecondSubject":"Java"}); { "acknowledged" : true, "insertedId" : 102 }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.searchMultipleFieldsDemo.find().pretty();
这将产生以下输出
{ "_id" : 100, "FirstSubject" : "Java", "SecondSubject" : "MongoDB" } { "_id" : 101, "FirstSubject" : "MongoDB", "SecondSubject" : "MySQL" } { "_id" : 102, "FirstSubject" : "MySQL", "SecondSubject" : "Java" }
以下是在MongoDB中的多个字段中搜索多个值的查询
> db.searchMultipleFieldsDemo.find({"$text":{"$search":"Java MongoDB"}});
这将产生以下输出
{ "_id" : 102, "FirstSubject" : "MySQL", "SecondSubject" : "Java" } { "_id" : 100, "FirstSubject" : "Java", "SecondSubject" : "MongoDB" } { "_id" : 101, "FirstSubject" : "MongoDB", "SecondSubject" : "MySQL" }