繁体   English   中英

将double []放在文档的字段中

[英]putting a double[] inside a field of a document

我试图创建一个文档,然后将其放入mongo数据库中。 创建文档时,其中一个字段的类型为double[] 我使用下一行代码将此字段添加到文档中:

Document loc = new Document();
loc.put("position", new Document("type", "Point").append("cords", new double[]{32.05, 35.15}));

当我尝试打印出position字段的内容时,我得到下一个输出: position = Document{{type=Point, cords=[D@d455b8}}

我使用下面的代码将其打印出来:

private void printout(Document d){
    Set<Entry<String, Object>> ks = d.entrySet();
    for (Entry e : ks){
        System.out.println(e.getKey() + " = " + e.getValue());
    }
    System.out.println("");
}   

问题是,为什么我在打印文档键和值时看不到实际数字? 另一个问题是,如果我以这种方式存储文档,我是否能够使用$near运算符查找文档中某个位置最接近其他位置的文档?

任何帮助,将不胜感激,谢谢。

我认为您做对了。 打印不起作用的原因与mongodb无关。

只需尝试以下方法:

    double [] cords = new double[]{32.05, 35.15};
    System.out.println(cords);//outputs [D@311d617d
    System.out.println(Arrays.toString(cords)); // outputs [32.05, 35.15]

打印数组的一种可读方式是使用Arrays.toString(..) 这就是您的for循环中发生的事情。 但是在插入之前,它将转换为正确的BSON类型。

$near查询中使用它看起来也不错。

问题解决了。 显然,应该使用一个列表才能将数组插入到mongoDB文档中。

List<Double> cordlist = new ArrayList<Double>(); 
        cordlist.add(32.05); 
        cordlist.add(35.15);
        loc.put("position", new Document("type", "Point").append("cords", cordlist));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM