我们收集了一系列的股票:
{
"_id" : ObjectId("xxxxxxx"),
"scrip" : "3647"
}
{
"_id" : ObjectId("yyyyyy"),
"scrip" : "5647"
}
...
我们只是试图使用Java驱动程序3.7以字符串数组形式返回脚本代码
ArrayList<Document> scriplist = scrips.aggregate(Arrays.asList(
Aggregates.group(
Accumulators.push("scripids",
new Document("_id", "$id").
append("scripids", "$scripid"))
)
)).into(new ArrayList<>());
System.out.println(scriplist.toString());
预期输出为['3647','5647']
。
但是,我们得到了'Can't find a codec for class com.mongodb.client.model.BsonField.'
异常。
该怎么办?
答案 0 :(得分:1)
以下查询可以为我们提供预期的输出:
private boolean externalUpdate = false;
...
list.addListener((ListChangeListener) c -> {
if (!externalUpdate) {
// TODO: send update to server
}
});
...
public void receiveServerUpdate(...) {
externalUpdate = true;
// TODO: modify list
externalUpdate = false;
}
输出:
db.scrips.distinct("scrip");
Java中的等效代码:
["3647","5647"]
“脚本”集将保存不同的脚本。
一些其他方法可以做到这一点:
DistinctIterable<String> iterable = scrips.distinct("scrip", String.class);
List<String> scrips = new ArrayList<>();
Block<String> block = scrip -> scrips.add(scrip);
iterable.forEach(block);
Java代码:
db.scrips.aggregate([
{
$group:{
"_id":"$scrip"
}
},
{
$group:{
"_id":null,
"scrips":{
$push:"$_id"
}
}
},
{
$project:{
"_id":0
}
}
])
scrips.aggregate(
Arrays.asList(Aggregates.group("$scrip"), Aggregates.group(null, Accumulators.push("scrips", "$_id")),
Aggregates.project(Projections.exclude("_id"))));
Java代码:
db.scrips.aggregate([
{
$group:{
"_id":null,
"scrips":{
$addToSet:"$scrip"
}
}
},
{
$project:{
"_id":0
}
}
])