按 MongoDB 中的特定欄位搜尋


我們首先使用文件建立一個集合 −

> db.demo371.insertOne({"Name":"David","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57f6982ae06a1609a00af2")
}
> db.demo371.insertOne({"Name":"John","CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57f69e2ae06a1609a00af3")
}
> db.demo371.insertOne({"Name":"Bob","CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57f6a42ae06a1609a00af4")
}
> db.demo371.insertOne({"Name":"Mike","CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57f6ba2ae06a1609a00af5")
}

使用 find() 方法顯示集合中的所有文件 −

> db.demo371.find();

這將產生以下輸出 −

{ "_id" : ObjectId("5e57f6982ae06a1609a00af2"), "Name" : "David", "CountryName" : "US" }
{ "_id" : ObjectId("5e57f69e2ae06a1609a00af3"), "Name" : "John", "CountryName" : "UK" }
{ "_id" : ObjectId("5e57f6a42ae06a1609a00af4"), "Name" : "Bob", "CountryName" : "AUS" }
{ "_id" : ObjectId("5e57f6ba2ae06a1609a00af5"), "Name" : "Mike", "CountryName" : "US" }

以下是按特定欄位搜尋的查詢 −

> db.demo371.find({ $or: [ { Name: "David" }, { CountryName: "UK"} ] } )

這將產生以下輸出 −

{ "_id" : ObjectId("5e57f6982ae06a1609a00af2"), "Name" : "David", "CountryName" : "US" }
{ "_id" : ObjectId("5e57f69e2ae06a1609a00af3"), "Name" : "John", "CountryName" : "UK" }

更新於: 02-4-2020

273 次瀏覽

開啟你的 事業

透過完成本課程並獲得認證

開始學習
廣告
© . All rights reserved.