Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Truy xuất tài liệu cụ thể trong MongoDB với các phần tử mảng

Để truy xuất một tài liệu cụ thể, hãy sử dụng ký pháp dấu chấm (dot notation) trong phương thức find() của MongoDB. Hãy tạo một collection với các tài liệu như sau:

> db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"Oppo"}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3ea9b04263e90dac943e5") }
> db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"Samsung"}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3eaa404263e90dac943e6") }
> db.demo672.insertOne({Brand:[{CategoryName:"Mobile","Name":"OnePlus"}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3eacc04263e90dac943e7") }

Hiển thị tất cả tài liệu từ collection bằng phương thức find():

> db.demo672.find();

Kết quả trả về:

{ "_id" : ObjectId("5ea3ea9b04263e90dac943e5"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "Oppo" } ] }
{ "_id" : ObjectId("5ea3eaa404263e90dac943e6"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "Samsung" } ] }
{ "_id" : ObjectId("5ea3eacc04263e90dac943e7"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "OnePlus" } ] }

Truy vấn để lấy tài liệu cụ thể có tên thương hiệu là "OnePlus":

> db.demo672.find({"Brand.Name":"OnePlus"});

Kết quả:

{ "_id" : ObjectId("5ea3eacc04263e90dac943e7"), "Brand" : [ { "CategoryName" : "Mobile", "Name" : "OnePlus" } ] }