要在数组项上实现$dateToString,请aggregate()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo104.insertOne( ... { ... ... "AppName" : "Online Book", ... "Details" : [ ... { ... "ClientName" : "Chris", ... "Deadline" : new ISODate("2020-03-10") ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2ed7fd9fd5fd66da21446f") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo104.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e2ed7fd9fd5fd66da21446f"), "AppName" : "Online Book", "Details" : [ { "ClientName" : "Chris", "Deadline" : ISODate("2020-03-10T00:00:00Z") } ] }
以下是对数组项实现$dateToString的查询-
> db.demo104.aggregate([ ... { "$match": {}}, ... { "$project": { ... "title": 1, ... "Details": { ... "$map": { ... "input": "$Details", ... "as": "out", ... "in": { ... "ClientName": "$$out.ClientName", ... "Deadline": { ... "$dateToString": { "format": "%m", "date": "$$out.Deadline" } ... } ... } ... } ... } ... }} ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e2ed7fd9fd5fd66da21446f"), "Details" : [ { "ClientName" : "Chris", "Deadline" : "03" } ] }