获取 MongoDB 集合中具有“isMarried”状态的所有嵌入式文档
若要获取所有嵌入式文档,请在 MongoDB 中使用 $project。让我们创建一个包含文档的集合 −
> db.demo220.insertOne({ ... "id":101, ... "FullName" : "John Doe", ... "EmailId" : "[email protected]", ... "ShippingDate" : new ISODate(), ... "details" : { "_id" :1001, "isMarried" :true } ...} ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3eaf5b03d395bdc213471d") } > db.demo220.insertOne( ...{ ... "id":102, ... "FullName" : "John Smith", ... "EmailId" : "[email protected]", ... "ShippingDate" : new ISODate(), ... "details" : { "_id" :1002, "isMarried" :false } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e3eaf5c03d395bdc213471e") }
使用 find() 方法显示集合中的所有文档 −
> db.demo220.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3eaf5b03d395bdc213471d"), "id" : 101, "FullName" : "John Doe", "EmailId" : "[email protected]", "ShippingDate" : ISODate("2020-02-08T12:53:47.876Z"), "details" : { "_id" : 1001, "isMarried" : true } } { "_id" : ObjectId("5e3eaf5c03d395bdc213471e"), "id" : 102, "FullName" : "John Smith", "EmailId" : "[email protected]", "ShippingDate" : ISODate("2020-02-08T12:53:48.991Z"), "details" : { "_id" : 1002, "isMarried" : false } }
以下是获取所有嵌入式文档的查询 −
> db.demo220.aggregate({ $project : { ... "isMarried" : "$details.isMarried", ... "detailsId" : "$details_id", } });
这将产生以下输出 −
{ "_id" : ObjectId("5e3eaf5b03d395bdc213471d"), "isMarried" : true } { "_id" : ObjectId("5e3eaf5c03d395bdc213471e"), "isMarried" : false }
广告