0

Stuck with an issue here.

I have 2 or more mongodb collections which need to be searched and the result of the search should be put into a JSON string.

// First collection
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "car");
DBCursor cur = collectionOne.find(dbo);

// Second collection
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "car");
DBCursor cur = collectionTwo.find(dbo);

The structure of the of the collection are not the same, but they do have a few common field, like 'transport','title', 'id' which are the fields that need to go in the json.

So combine the results of two searches into a single JSON response.

How would I do this?

Thanks for any help or suggestions!

Steven Filipowicz
  • 389
  • 2
  • 10
  • 25
  • It's not clear what you're trying to do. What's the output you want? (The subject isn't clear "how would I do this?") Are you trying to somehow combine the results of two searches into a single response, when the data is in two different collections? (Merge the results into a single POJO and serialize to JavaScript/JSON) – WiredPrairie Jan 02 '13 at 13:39
  • Yes trying to combine the results of two searches into a single response. – Steven Filipowicz Jan 02 '13 at 13:46
  • Take a look at http://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb which deals with the same question. – James Wahlin Jan 02 '13 at 15:29
  • Merge the objects returned from the query into a common POJO and serialize it. Is there something other than that you're looking for? (You can't do two queries on distinct collections and merge the results in mongoDB and return them as a single response.) You'll need to do that in your client code. – WiredPrairie Jan 02 '13 at 15:29

1 Answers1

0

Given the facts that the query criteria is unique across the collections, and MongoDB is a schema-free, no-SQL database, Actually you can just use one collection for all the data sets and don't need to consolidate different collections at all. Just like:

BasicDBObject query = new BasicDBObject();
query.append("transport", "car");
BasicDBObject fields = new BasicDBObject();
fields.append("transport", "1");
fields.append("title", "1");          //get the fields
DBCursor cur = collection.find(query, fields);
coderLMN
  • 3,076
  • 1
  • 21
  • 26