0

I am writing a RESTful web service where in I want to return a XML after doing a query in Mongo using a Mongo Connector.

I have searched alot and i didnt find any good tutorial online. Need Help XD

public class MongoConnector {
    private MongoClient mongoClient;

    public MongoConnector(){
        //TODO: Parameterizar connection string
        mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
    }

    public String getData(String databaseName, String collectionName, String field, String value){
        MongoDatabase database = mongoClient.getDatabase(databaseName);//"restaurantsDB"
        MongoCollection<Document> collection = database.getCollection(collectionName);//"restaurants"
        Bson filter = eq(field, value);//borough, bronx

        return StreamSupport.stream(collection.find(filter).limit(10).spliterator(), false)
                .map(Document::toJson)
                .collect(Collectors.joining(", ", "[", "]")).toString();
    }

    public String aggregateDataByQueryString(String databaseName, String collectionName, String query){
        MongoDatabase database = mongoClient.getDatabase(databaseName);//"restaurantsDB"
        MongoCollection<Document> collection = database.getCollection(collectionName);//"restaurants"
        BasicDBObject q = BasicDBObject.parse(query);
        //Mapear o resultado para um array em JSON
        return StreamSupport.stream(collection.aggregate(Arrays.asList(q)).spliterator(), false)
                .map(Document::toJson)
                .collect(Collectors.joining(", ", "[", "]")).toString();
    }
}
Cardinal System
  • 2,749
  • 3
  • 21
  • 42
Miguel Costa
  • 5
  • 1
  • 2

1 Answers1

0

I checked out the MongoDB documentation, and poked around the internet a little, but I could not find anything defined within the API itself that can carry out your task. That being said, there are still a few options here that could work for you:

  1. Because org.bson.Document implements java.util.Map, you can look at How to convert XML to java.util.Map and vice versa as a potential solution.
  2. Because you are mapping your document to a JSON string before returning it, you could try Converting JSON to XML in Java as another potential solution.

I am not too familliar with MongoDB, but I believe these solutions will work since a Document object is "a representation of a document as a Map," and because it can be cleanly converted to a JSON string.

Cardinal System
  • 2,749
  • 3
  • 21
  • 42