MongoDB
 sql >> Baza danych >  >> NoSQL >> MongoDB

Pole $concat z indeksem w $map mongodb?

Chociaż z pewnością poleciłbym to zrobić po stronie klienta, a nie wewnątrz MongoDB, oto jak możesz uzyskać to, czego chcesz - dość brutalna siła, ale działająca:

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. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. jak wykonać zapytanie za pomocą określonego pola zamiast id w ekspresowym js

  2. Dokument osadzony a odniesienie w modelu projektowania mangusty?

  3. mongodb dostęp do poddokumentów

  4. Używanie kopii zapasowych do naprawy typowych scenariuszy awarii dla MongoDB

  5. różnica między agregacją ($match) a znajdowaniem w MongoDB?