1

In python/pymongo, creating GeoSpatial index is quite trivial:

db.collection.create_index([("loc", GEO2D)], min=-100, max=100)

After that I can insert data using "loc" field.

But in C++/mongocxx, after referring mongocxx document (http://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/) and GeoSpatial docement, I still cannot figure out how to do this.

Could anyone kindly show me how to deal with Geospatial index in C++? Thanks in advance.

1 Answer 1

2

You can create a GeoSpatial index with the C++ driver in a similar way to the Python driver; the main difference is that instead of passing the minimum and maximum as direct arguments to create_index, they're instead set in an options::index object which is then passed to create_index. Here's a short program that creates the index you described above using the C++ driver:

#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/options/index.hpp>
#include <mongocxx/uri.hpp>

using namespace mongocxx;
using bsoncxx::builder::basic::kvp;

int main() {
    instance inst{};

    client conn{uri{}};
    auto coll = conn["db_name"]["coll_name"];

    bsoncxx::builder::basic::document index_doc;
    index_doc.append(kvp("loc", "2d"));

    coll.create_index(
        index_doc.extract(),
        options::index{}
            .twod_location_min(-100).twod_location_max(100));

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.