代码之家  ›  专栏  ›  技术社区  ›  Ashh

$map mongodb中有索引的$concat字段?[复制品]

  •  0
  • Ashh  · 技术社区  · 6 年前

    我有以下收藏

    {
        "_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"
    }
    

    我能换衣服吗 createdAt 格式化为此 Thu Jan 18 2018 使用 $dateToString 或者别的什么????

    提前谢谢!!!!

    1 回复  |  直到 6 年前
        1
  •  1
  •   dnickless    6 年前

    虽然我当然建议你在客户端而不是在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
        }
    }])