sql >> Database teknologi >  >> NoSQL >> MongoDB

$concat felt med indeks i $map mongodb?

Selvom jeg bestemt vil anbefale dig at gøre det på klientsiden i modsætning til inde i MongoDB, her er, hvordan du kan få det, du vil have - temmelig brute-force, men fungerer:

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
    }
}])



  1. Konvertering af DBObject til Java Object, mens du henter værdier fra MongoDB

  2. Visualisering af din klyngetopologi i ClusterControl

  3. Upsert Ordbog i MongoDb

  4. meteor:hvordan kan jeg sikkerhedskopiere min mongo-database