1

I have a structure like this in my database:

{
  {
     "document_id" : 35,
     "transport" : ["car", "plane", "train", "boat"]
  },

  {
     "document_id" : 36,
     "transport" : ["car", "bike", "train"]
  }
}

How would I do a search query to find a document/record with for example transport 'plane'?

Thanks for any help.

Steven

0

3 Answers 3

3

from MongoShell

db.find({transport:"plane"}) would do.

MongoDB will search the entire array to match the query in case the value is an array.

Using Java Driver.

Yous first get the Mongo collection

List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "plane");
DBCursor cur = collection.find(dbo);
while (cur.hasNext()) {
            list.add(JSONHelper.toJSON(cur.next().toMap()));
        }
Sign up to request clarification or add additional context in comments.

Comments

3

To search for an array containing an element, you can just check for that element against the array.

So, just using: -

db.collection.find({transport:"plane"})

would give you what you want.

Here's the implementation in Java: -

BasicDBObject doc = new BasicDBObject("document_id", 35)
                             .append("transport", new String[] {"car", "plane"});

BasicDBObject doc2 = new BasicDBObject("document_id", 36)
                             .append("transport", new String[] {"car"});

coll.insert(doc);
coll.insert(doc2);

DBObject query = new BasicDBObject("transport", "plane");
DBCursor cursor = coll.find(query, new BasicDBObject("_id", 0));

while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

Output : -

{ "document_id" : 35 , "transport" : [ "car" , "plane"]}

Comments

0
@Document(collection = "document")
public class Transport {


private ObjectId document_id;

private ArrayList transport;



}


//

   List<String> list = new ArrayList<String>();
        list.add("car");
        list.add("plane");
        list.add("train");
        list.add("boat");

Transport transport;

transport.setTransport(list);

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.