本文介绍了$ near通过Java查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Java在集合上运行$ near查询.我不确定如何为此使用QeuryBuilder或BasicDbObject.通过Java代码运行$ near查询的正确方法是什么.以下是我的文档结构代码. 位置"属性将类型存储为点,坐标将存储经纬度.我已经在这个集合上创建了一个2dsphere索引.

I want to run a $near query on a collection through Java. I am not sure how to use QeuryBuilder or BasicDbObject for this. What is the correct way to run $near query through Java code. Below is my code for document structure. "location" attribute stores type as point and coordinates stores the lat-long. I have created a 2dsphere index on this collection.

BasicDBObject doc = new BasicDBObject("attr1", nextLine[0])
                          .append("attr2", nextLine[1])
                          .append("edge-metro-code", nextLine[6])
                          .append("location", new BasicDBObject("type", "Point")
                                                        .append("coordinates",latLong)) 
                          .append("attr3", nextLine[9])
                          .append("attr4", nextLine[10])

推荐答案

首先,您需要一个maxDistance和一个参考点来计算附近的文档.下面的代码显示了如何构建一个DBObject来查询附近的文档.

First you'll need a maxDistance and a referential point to calculate near documents. The code bellow shows how to build a DBObject to query near documents.

double[] coords = new double[2];
long distance = 100;

DBObject query = BasicDBObjectBuilder.start()
    .push("location")
        .add("$maxDistance", distance)
        .push("$near")
            .push("$geometry")
                .add("type", "Point")
                .add("coordinates", coords)
    .get();

这将导致该json:

{
    "location": {
        "$maxDistance": 100,
        "$near": {
            "$geometry": {
                "type": "Point",
                "coordinates": [
                    0,
                    0
                ]
            }
        }
    }
}

如果您使用的是mongodb 2.2,则上面的代码将不起作用.我必须使用以下内容:

If you're using mongodb 2.2, the code above will not work. I have to use the following:

double[] coords = new double[2];
long distance = 100;

DBObject query = BasicDBObjectBuilder.start()
    .push("location")
        .add("$maxDistance", distance)
        .add("$near", coords)
    .get();

json为:

{
    "location" : {
        "$maxDistance" : 100,
        "$near" : [
            0,
            0
        ]
    }
}

您可以在此处找到有关近距离查询的更多信息:

You can find more informations about near queries here:

http://docs.mongodb.org/manual/reference/operator/near /

这篇关于$ near通过Java查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 18:06