在 MongoDB 中,使用 $in 搜尋比執行多次單一搜索更快嗎?
是的,使用 $in 更快。我們看一個示例並建立一個包含文件的集合 -
> db.demo653.insertOne({subject:"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea04b274deddd72997713c0")
}
> db.demo653.insertOne({subject:"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea04b304deddd72997713c1")
}
> db.demo653.insertOne({subject:"Java"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea04b354deddd72997713c2")
}
> db.demo653.insertOne({subject:"C"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea04b384deddd72997713c3")
}
> db.demo653.insertOne({subject:"C++"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea04b3b4deddd72997713c4")
}使用 find() 方法從集合中顯示所有文件 -
> db.demo653.find();
這將產生以下輸出 -
{ "_id" : ObjectId("5ea04b274deddd72997713c0"), "subject" : "MySQL" }
{ "_id" : ObjectId("5ea04b304deddd72997713c1"), "subject" : "MongoDB" }
{ "_id" : ObjectId("5ea04b354deddd72997713c2"), "subject" : "Java" }
{ "_id" : ObjectId("5ea04b384deddd72997713c3"), "subject" : "C" }
{ "_id" : ObjectId("5ea04b3b4deddd72997713c4"), "subject" : "C++" }以下是使用 $in 並比執行多次單一搜索更快地進行搜尋的查詢 -
> db.demo653.find({subject:{$in:["MySQL","C++","C"]}});這將產生以下輸出 -
{ "_id" : ObjectId("5ea04b274deddd72997713c0"), "subject" : "MySQL" }
{ "_id" : ObjectId("5ea04b384deddd72997713c3"), "subject" : "C" }
{ "_id" : ObjectId("5ea04b3b4deddd72997713c4"), "subject" : "C++" }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP