在 MongoDB 中搜索多條文件?


要在 MongoDB 中搜索多條文件,請使用 $in。讓我們建立包含文件的集合 -

> db.demo161.insertOne({"ClientId":101,"ClientName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3577cafdf09dd6d0853a09")
}
> db.demo161.insertOne({"ClientId":102,"ClientName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3577d0fdf09dd6d0853a0a")
}
> db.demo161.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3577dffdf09dd6d0853a0b")
}
> db.demo161.insertOne({"ClientId":104,"ClientName":"Carol","ClientAge":31});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3577eefdf09dd6d0853a0c")
}

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

> db.demo161.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e3577d0fdf09dd6d0853a0a"), "ClientId" : 102, "ClientName" : "David" }
{ "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31 }

以下是 MongoDB 中搜索多條文件的查詢 -

> db.demo161.find({ClientId:{$in:[101,103,104]}});

這將產生以下輸出 -

{ "_id" : ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31 }

更新於:2020 年 4 月 1 日

174 次瀏覽

啟動 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.