Node.js $map mongodb中有索引的$concat字段?
我有以下收藏Node.js $map mongodb中有索引的$concat字段?,node.js,mongodb,mongoose,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我有以下收藏 { "_id" : ObjectId("5b16405a8832711234bcfae7"), "createdAt" : ISODate("2018-06-05T07:48:45.248Z"), "firstName": "Bruce", "lastName": "Wayne" }, { "_id" : ObjectId("5b16405a8832711234bcfae8"), "createdAt" : ISODate("2018
{
"_id" : ObjectId("5b16405a8832711234bcfae7"),
"createdAt" : ISODate("2018-06-05T07:48:45.248Z"),
"firstName": "Bruce",
"lastName": "Wayne"
},
{
"_id" : ObjectId("5b16405a8832711234bcfae8"),
"createdAt" : ISODate("2018-06-05T07:48:45.248Z"),
"firstName": "Clerk",
"lastName": "Kent"
},
{
"_id" : ObjectId("5b16405a8832711234bcfae9"),
"createdAt" : ISODate("2018-06-05T07:48:45.248Z"),
"firstName": "Peter",
"lastName": "Parker"
}
我需要$project
使用$concat
和'INV-00'+根元素的索引再创建一个键索引
我的输出应该是这样的
{
"_id" : ObjectId("5b16405a8832711234bcfae7"),
"createdAt" : ISODate("2018-06-05T07:48:45.248Z"),
"firstName": "Bruce",
"lastName": "Wayne",
"index": "INV-001"
},
{
"_id" : ObjectId("5b16405a8832711234bcfae8"),
"createdAt" : ISODate("2018-06-05T07:48:45.248Z"),
"firstName": "Clerk",
"lastName": "Kent",
"index": "INV-002"
},
{
"_id" : ObjectId("5b16405a8832711234bcfae9"),
"createdAt" : ISODate("2018-06-05T07:48:45.248Z"),
"firstName": "Peter",
"lastName": "Parker",
"index": "INV-003"
}
我是否可以在2018年1月18日星期四使用或其他方法将createdAt
格式更改为此格式
提前感谢 我当然会建议您在客户端而不是在MongoDB内部这样做,但以下是您可以得到想要的东西的方法-非常暴力但有效:
db.collection.aggregate([
// you should add a $sort stage here to make sure you get the right indexes
{
$group: {
_id: null, // group all documents into the same bucket
docs: { $push: "$$ROOT" } // just to create an array of all documents
}
}, {
$project: {
docs: { // transform the "docs" field
$map: { // into something
input: { $range: [ 0, { $size: "$docs" } ] }, // an array from 0 to n - 1 where n is the number of documents
as: "this", // which shall be accessible using "$$this"
in: {
$mergeObjects: [ // we join two documents
{ $arrayElemAt: [ "$docs", "$$this" ] }, // one is the nth document in our "docs" array
{ "index": { $concat: [ 'INV-00', { $substr: [ { $add: [ "$$this", 1 ] }, 0, -1 ] } ] } } // and the second document is the one with our "index" field
]
}
}
}
}
}, {
$unwind: "$docs" // flatten the result structure
}, {
$replaceRoot: {
newRoot: "$docs" // restore the original document structure
}
}])
更改createdAt键格式将如何帮助您推断文档的索引?试图了解您试图记录的内容我可以使用$dateToString或其他工具将createdAt格式更改为2018年1月18日星期四,我只是想知道这可能吗?。。。与索引部分无关@AstroThis应该会有帮助:。@NeilLunn:a)您似乎没有阅读我的起始免责声明,该免责声明实际上与您在上述问题评论中的建议相同。b) 并非每个人的收藏中都有数十亿份文件。c) 我很清楚的BSON限制不适用于聚合管道内部。