Gemäß meiner letzten Frage ( Anzahl der Dokumente nach mehreren Bereichen abfragen, die den Beginn/das Ende des Bereichs mit der Anzahl der übereinstimmenden Elemente zurückgeben ) habe ich eine Abfrage erstellt, um die Anzahl der Dokumente in mehreren, möglicherweise überlappenden Datumsbereichen zu überprüfen.
Die Abfrage funktioniert auf MongoDB 4.4, aber ich muss sie auch auf 4.2 ausführen. Auf MongoDB 4.2 erhalte ich die folgende Fehlermeldung:
Mongo Server error (MongoCommandException): Command failed with error 168 (InvalidPipelineOperator): 'Unrecognized expression '$first'' on server localhost:27017.
The full response is:
{
"ok": 0.0,
"errmsg": "Unrecognized expression '$first'",
"code": 168.0,
"codeName": "InvalidPipelineOperator"
}
Wie würden Sie die Aggregationsprojektion schreiben, um die gleiche Ergebnisstruktur zu erreichen. Hier ist der vollständige Code mit Dateneinrichtung
db.createCollection("object_location_tracking");
db.getCollection("object_location_tracking").insertMany([
{
_id: "1",
locationId: "locationA",
objectId: "objectA",
timestamp: ISODate("2020-01-01T00:00:00Z")
},
{
_id: "2",
locationId: "locationB",
objectId: "objectA",
timestamp: ISODate("2020-01-01T00:00:00Z")
},
{
_id: "3",
locationId: "locationA",
objectId: "objectB",
timestamp: ISODate("2019-01-01T00:00:00Z")
},
{
_id: "4",
locationId: "locationB",
objectId: "objectB",
timestamp: ISODate("2020-01-01T00:00:00Z")
}
]);
db.getCollection("object_location_tracking").aggregate([
{$facet: {
"first_bucket_id": [
{$match: {"objectId":"objectA",
"locationId":"locationA",
"timestamp": {$gte: new ISODate('2020-01-01'),
$lt: new ISODate('2020-12-31')}
}},
{$count: "N"}
],
"second_bucket_id": [
{$match: {"objectId":"objectA",
"locationId":"locationA",
"timestamp": {$gte: new ISODate('2020-01-01'),
$lt: new ISODate('2022-12-31')}
}},
{$count: "N"}
],
"third_bucket_id": [
{$match: {"objectId":"objectA",
"locationId":"locationB",
"timestamp": {$gte: new ISODate('2022-01-01'),
$lt: new ISODate('2022-12-31')}
}},
{$count: "N"}
]
}},
{
$set: {
first_bucket_id: { $first: "$first_bucket_id.N"},
second_bucket_id: { $first: "$second_bucket_id.N"},
third_bucket_id: { $first: "$third_bucket_id.N"}
}
}
, {
$project: {
first_bucket_id: 1,
second_bucket_id: 1,
third_bucket_id: 1
}
}
]);
Lösung des Problems
Sie verwenden das erste Array-Element, das, wie Sie sehen, ein neuer Operator ist, der für Version 4.4 hinzugefügt wurde
Zum Glück für Sie ist dies recht einfach zu überwinden, indem Sie einfach $arrayElemAt wie folgt verwenden:
{
$set: {
first_bucket_id: {$arrayElemAt: ["$first_bucket_id.N", 0]},
second_bucket_id: {$arrayElemAt: ["$second_bucket_id.N", 0]},
third_bucket_id: {$arrayElemAt: ["$third_bucket_id.N", 0]}
}
}
Keine Kommentare:
Kommentar veröffentlichen