如何通过 MongoDB 中子文档的条件查询文档?
我们首先创建一个带有文档的集合 -
> db.demo394.insertOne( ... { ... ... details: [ ... { ... _id: '1', ... startDate: '2018-01-11T07:00:00.000Z', ... endDate: '2019-01-12T07:59:59.999Z' ... }, ... { ... _id: '2', ... startDate: '2019-01-21T07:00:00.000Z', ... endDate: '2020-01-04T07:59:59.999Z' ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e716817aa3ef9ab8ab202") }
在集合中显示所有文档,使用 find() 方法 -
> db.demo394.find();
将生成以下输出 -
{ "_id" : ObjectId("5e5e716817aa3ef9ab8ab202"), "details" : [ { "_id" : "1", "startDate" : "2018-01-11T07:00:00.000Z", "endDate" : "2019-01-12T07:59:59.999Z" }, { "_id" : "2", "startDate" : "2019-01-21T07:00:00.000Z", "endDate" : "2020-01-04T07:59:59.999Z" } ] }
以下是如何通过子文档中的条件查询文档 -
> db.demo394.find({ ... $expr: { ... $let: { ... vars: { "d": { $arrayElemAt: [ "$details", -1 ] } }, ... in: { $eq: [ "$$d.endDate", "2020-01-04T07:59:59.999Z" ] } ... } ... } ... })
将生成以下输出 -
{ "_id" : ObjectId("5e5e716817aa3ef9ab8ab202"), "details" : [ { "_id" : "1", "startDate" : "2018-01-11T07:00:00.000Z", "endDate" : "2019-01-12T07:59:59.999Z" }, { "_id" : "2", "startDate" : "2019-01-21T07:00:00.000Z", "endDate" : "2020-01-04T07:59:59.999Z" } ] }
广告