Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để truy vấn trường danh sách trong MongoDB?

Để hiểu truy vấn trên trường danh sách và / hoặc, bạn có thể tạo một bộ sưu tập với các tài liệu.

Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -

> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[33,40,50,60,70]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9522d316f542d757e2b444")
}
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[87,67,79,98,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c95230916f542d757e2b445")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -

> db.andOrDemo.find().pretty();

Sau đây là kết quả -

{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
{
   "_id" : ObjectId("5c95230916f542d757e2b445"),
   "StudentName" : "Larry",
   "StudentScore" : [
      87,
      67,
      79,
      98,
      90
   ]
}

Đây là truy vấn trên trường danh sách.

Truy vấn như sau -

> db.andOrDemo.find({"StudentScore":70}).pretty();

Sau đây là kết quả:

{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}

Trường hợp 3 - Đây là truy vấn cho hoặc trường danh sách.

Truy vấn như sau -

> db.andOrDemo.find({"$or":[ {"StudentScore":60}, {"StudentScore":90}]}).pretty();

Đầu ra mẫu -

{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
{
   "_id" : ObjectId("5c95230916f542d757e2b445"),
   "StudentName" : "Larry",
   "StudentScore" : [
      87,
      67,
      79,
      98,
      90
   ]
}