Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Java Driver Array

Tags:

java

mongodb

I am trying to save a set of tags within a mongodb document e.g.

{
    id:"104454",
    tags:["tag1", "tag2"]
}

I am struggling to figure out how to do this with the Java Driver though. I thought I would use BasicDBList but this doesnt seem to be right.

Could someone help please?

Thanks in advance.

like image 432
christophmccann Avatar asked Dec 02 '25 20:12

christophmccann


2 Answers

You can use simple arrays and then you can do something like:

doc.put("tags", array)
like image 140
spami Avatar answered Dec 04 '25 09:12

spami


When saving arrays into MongoDB with Java, according to the online doc, you can use anything that extends List.

So, using your example, that would be something like the following:

ArrayList tags = new ArrayList();
tags.add("tag1");
tags.add("tag2");

BasicDBObject doc = new BasicDBObject(new ObjectId(), tags);
like image 22
Rodrigue Avatar answered Dec 04 '25 09:12

Rodrigue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!