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

Nhận tất cả các tài liệu nhúng có trạng thái “isMarried” trong bộ sưu tập MongoDB

Để lấy tất cả các tài liệu nhúng, hãy sử dụng $ project trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo220.insertOne({
...   "id":101,
...   "FullName" : "John Doe",
...   "EmailId" : "john12@gmail.com",
...   "ShippingDate" : new ISODate(),
...   "details" : { "_id" :1001, "isMarried" :true }
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3eaf5b03d395bdc213471d")
}
> db.demo220.insertOne(
...{
...   "id":102,
...   "FullName" : "John Smith",
...   "EmailId" : "johnsmith@gmail.com",
...   "ShippingDate" : new ISODate(),
...   "details" : { "_id" :1002, "isMarried" :false }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3eaf5c03d395bdc213471e")
}

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 () -

> db.demo220.find();

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5e3eaf5b03d395bdc213471d"), "id" : 101, "FullName" : "John Doe", "EmailId" : "john12@gmail.com", "ShippingDate" : ISODate("2020-02-08T12:53:47.876Z"), "details" : { "_id" : 1001, "isMarried" : true } }
{ "_id" : ObjectId("5e3eaf5c03d395bdc213471e"), "id" : 102, "FullName" : "John Smith", "EmailId" : "johnsmith@gmail.com", "ShippingDate" : ISODate("2020-02-08T12:53:48.991Z"), "details" : { "_id" : 1002, "isMarried" : false } }

Sau đây là truy vấn để lấy tất cả các tài liệu được nhúng -

> db.demo220.aggregate({ $project : {
...   "isMarried" : "$details.isMarried",
...   "detailsId" : "$details_id", } });

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5e3eaf5b03d395bdc213471d"), "isMarried" : true }
{ "_id" : ObjectId("5e3eaf5c03d395bdc213471e"), "isMarried" : false }