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

Zagregowana liczba zwrotów MongoDB równa 0, jeśli nie ma dokumentów

Zastrzeżenie:nie polecam robić tego po stronie serwera (czyli wewnątrz MongoDB), ale raczej zajmować się tą sprawą po stronie klienta.

To powiedziawszy, oto ogólne rozwiązanie twojego problemu, które powinno być łatwe do dostosowania do twojego konkretnego przypadku.

Wyobraź sobie, że masz następujące dokumenty (lub dane wyjściowe z potoku agregacji, jak w twoim przykładzie):

{
    "category" : 1
}
{
    "category" : 1
}
// note the missing { category: 2 } document here
{
    "category" : 3
}

Poniższy potok utworzy puste zasobniki (więc dokumenty z liczbą 0 dla wartości „luki”, których brakuje w zakresie wartości w category pole - w tym przypadku liczba 2):

var bucketSize = 1;

db.getCollection('test').aggregate({
    $group: {
        _id: null, // throw all documents into the same bucket
        "min": { $min: "$category" }, // just to calculate the lowest
        "max": { $max: "$category" }, // and the highest "category" value 
        "docs": { $push: "$$ROOT" } // and also keep the root documents
    }
}, {
    $addFields: {
        "docs": { // modify the existing docs array - created in the previous stage
            $concatArrays: [ // by concatenating
                "$docs", // the existing docs array
                {
                    $map: { // with some other array that will be generated
                        input: {
                            $range: [ "$min", "$max", bucketSize ] // based on the min and max values and the bucket size
                        },
                        as: "this",
                        in: { // but represented not as a plain number but as a document that effectively creates a bogus document
                            "category": "$$this", // the bogus category will be set to the respective value
                            "bogus": 1 // marker that allows us not to count this document in the next stage and still get a bucket from $group
                        }
                    }
                }
            ]
        }
    }
}, {
    $unwind: "$docs" // flatten the "docs" array which will now contain the bogus documents, too
}, {
    $group: {
        _id: "$docs.category", // group by category
        "count": { // this is the result we are interested in
            $sum: { // which will be aggregated by calculating the sum for each document of
                $cond: [ // either 0 or 1 per document
                    { $eq: [ "$docs.bogus", 1 ] }, // depending on whether the document should count as a result or not
                    0,
                    1
                ]
            }
        }
    }
})

Wynikiem powyższego zapytania będzie:

{
    "_id" : 2,
    "count" : 0.0 // this is what we wanted to achieve
}
{
    "_id" : 3,
    "count" : 1.0 // correct number of matches
}
{
    "_id" : 1,
    "count" : 2.0 // correct number of matches
}



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Mangusta:jak używać kruszywa i znajdować razem

  2. Błąd:getaddrinfo ENOTFOUND w nodejs do pobrania wywołania

  3. Generuj PDF za pomocą biblioteki JasperReports i MongoDB

  4. MongoDB:forEach vs fetch + each

  5. Znajdź wszystkie dokumenty w ciągu ostatnich n dni