Reputation: 101
Can someone help me converting the below query to java code?
I have written the following query in java as below but am getting below error,
Command failed with error 168: 'Unrecognized expression '$push'' on server. The full response is { "ok" : 0.0, "errmsg" : "Unrecognized expression '$push'", "code" : 168, "codeName" : "InvalidPipelineOperator" }
Query:
db.getCollection('xyz').aggregate([
{$match: { "_id":{$in: [{"a" : "NA","b" : "HXYZ","c" : "12345","d" : "CA"}]}
}
},
{ $unwind: '$bal' },
{
$sort: {'bal.date': -1}
},
{$group:
{"_id": "$_id",bal:{$push:'$bal'}}},
{ $project: {
balances: { $slice: ["$bal",2]}
}
}
])
Java Code:
List<Document> findDocument=collectionName.aggregate(
Arrays.asList(
Aggregates.match(in("_id",tempList)),
Aggregates.unwind("$bal"),
Aggregates.sort(Sorts.descending("bal.date")),
Aggregates.group(new Document("_id","$_id").append("bal",new Document("$push","$bal"))),
Aggregates.project(new Document("bal",new Document ("$slice",Arrays.asList("$bal", 2)))))).into(new ArrayList<Document>());
The Mongo DB version is 3.4. Can someone tell me why is $push not working ? Thanks in advance.
Upvotes: 0
Views: 1351
Reputation: 75994
You are pushing the document into id field instead create push document separately.
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.in;
import static com.mongodb.client.model.Sorts.*;
import static java.util.Arrays.*;
List<Document> results = collectionName.aggregate(
asList(
match(in("_id",tempList)),
unwind("$bal"),
sort(descending("bal.date")),
group("$_id", push("bal","$bal")),
project(new Document("bal",new Document ("$slice", asList("$bal", 2))))
)
).into(new ArrayList<>());
Upvotes: 1