I am using mongo db driver 2.11.2. I am bit puzzled how to insert/add an array to the BasicDBObject. All the example which I come across are does not show how to achieve this :(. In the below example how would I insert employees array in the dbo object ?
/*
{
"company" : "stackoverflow",
"established": "when I started coding"
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
*/
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("company", "stackoverflow");
basicDBObject.put("established", "when I started coding");
System.out.println(basicDBObject.toString());
}
Use the Arrays.asList as a contructor for the list. It's just a list. And .append() the object keys rather than "put". Again, it's just as HashMap interface:
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("company", "stackoverflow");
basicDBObject.append("established", "when I started coding");
basicDBObject.append("employees", Arrays.<DBObject>asList(
new BasicDBObject("firstName", "john")
.append("lastName", "doe"),
new BasicDBObject("firstName", "anna")
.append("lastName", "smith"),
new BasicDBObject("firstName", "peter")
.append("lastName", "jones")
));
System.out.println(basicDBObject.toString());
Related
I want to search a string in multiple values of all the MongoDB documents and return matched documents in return.
This is what I have tried to do it with one key
BasicDBObject object = new BasicDBObject();
object.put("firstName", Pattern.compile(value));
FindIterable<Document> documents = mongoCollection.find(object)
.skip(size*(index - 1)).limit(size);
for (Document document : documents) {
customerList.add(CustomerMapper.map(document));
}
return customerList;
How can I change it to search a value in all key/values?
I have firstName, lastName, email, phoneNumber in every document of the customers collection.
Suggestions?
Fixed it by using following code:
BasicDBObject orQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("firstName", new BasicDBObject("$regex", value).append("$options", "i")));
obj.add(new BasicDBObject("lastName", new BasicDBObject("$regex", value).append("$options", "i")));
obj.add(new BasicDBObject("email", new BasicDBObject("$regex", value).append("$options", "i")));
obj.add(new BasicDBObject("phoneNumber", new BasicDBObject("$regex", value).append("$options", "i")));
orQuery.put("$or", obj);
FindIterable<Document> documents = mongoCollection.find(orQuery)
This helped me to use selected keys to use for searching.
Im using Mongodb with java and im trying to create a document :
// mongo-java-driver-2.10.1 version
// create a document to store key and value
BasicDBObject document = new BasicDBObject();
document.put("name", "Yassine LD");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("addressLine1", "Sweet Home");
documentDetail.put("addressLine2", "New Street");
documentDetail.put("addressLine3", "CASABLANCA, MOROCCO");
document.put("address", documentDetail);
table.insert(document);
I got this error : The method insert(DBObject[]) in the type DBCollection is not applicable for the arguments (BasicDBObject)
It seems your insert method expects an array of DBObject. Assuming BasicDBObject is a sub-class of DBObject, you can write :
table.insert(new DBObject[] {document});
Is this type of query possible?
I need to query the database for data for a specified date for a set of specified stocks. So the data needs to have "this" date and be one of "these" symbols.
I have the following code:
public void findDateStockSet(String date, ArrayList<String> symbolSet) throws UnknownHostException {
this.stocks = this.getCollectionFromDB();
BasicDBObject objectToFind = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("date", date));
obj.add(new BasicDBObject("symbol", new BasicDBObject("$in", symbolSet)));
objectToFind.put("$and", obj);
DBCursor cursor = this.stocks.find(objectToFind);
System.out.println("Finding Stocks");
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println();
}
This always comes up null. Can someone explain how to make a query like this work?
You don't need to use $and operator, just build the query as the json below:
{ "date" : "20100223", "symbol" : { $in : [ "appl", "goog" ] } }
I like to use BasicDBObjectBuilder util class to build DBObjects. So your query will be:
DBObject query = BasicDBObjectBuilder.start()
.add("date", date)
.push("symbol")
.add("$in", symbolSet)
.get();
I'm using mongo 2.2.3 and the java driver.
My dilemma, I have to $push a field and value into an array, but I cant seem to figure out how to do this. A sample of my data:
"_id" : 1,
"scores" : [
{
"type" : "homework",
"score" : 78.97979
},
{
"type" : "homework",
"score" : 6.99
},
{
"type" : "quiz",
"score" : 99
}
]
I can $push in the shell:
db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})
but it's when I translate this into java I confuse my self and chuck my keyboard at a wall.
my java code (incomplete and wrong) so far:
DBObject find = new BasicDBObject("_id", 1);
DBObject push = new BasicDBObject("$push", new BasicDBObject(
"scores", new BasicDBObject()));
DBObject listItem = new BasicDBObject("scores", new BasicDBObject("type","quiz").append("score",99));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);
Since mongodb-driver 3.1. there is a builder class com.mongodb.client.model.Updates with appropriate methods for each update case. In this case this would be:
Document score = new Document().append("type", "quiz")
.append("score",99);
collection.updateOne(eq("_id", "1"),Updates.addToSet("scores", score));
If you're more comforable with the query format of the shell, you may find it's easier to use JSON.parse to contstruct your DBObject for the $push:
import com.mongodb.util.JSON;
String json = "{$push:{scores:{type:'quiz', score:99}}}";
DBObject push = (DBObject) JSON.parse(json);
Using Jongo, you can do as in the shell:
db.collection.update({_id:1},{$push:{scores:{type:"quiz", score:99}}})
Becomes in Java:
collection.update("{_id:1}").with("{$push:{scores:{type:#, score:#}}}", "quiz", 99);
No fancy DBObject needed ;-)
MongoDB Java driver can simplify this. Use $each instead of $push.
$each mongodb reference document
Java sample -
BasicDBObject addressSpec = new BasicDBObject();
addressSpec.put("id", new ObjectId().toString());
addressSpec.put("name", "one");
BasicDBObject addressSpec2 = new BasicDBObject();
addressSpec2.put("id", new ObjectId().toString());
addressSpec2.put("name", "two");
List<BasicDBObject> list = new ArrayList<>();
list.add(addressSpec); list.add(addressSpec2);
UpdateResult updateOne = individualCollection.updateOne(Filters.eq("_id", "5b7c6b612612242a6d34ebb6"),
Updates.pushEach("subCategories", list));
Im using java/mongodb. I would like to create a table (collection) with some users. Well, its working im just not sure about my coding style. Could be this good if i just want to add 3 new persons to the collection?
BasicDBObject doc = new BasicDBObject();
doc.put("name", "klaus");
doc.put("age", 30);
doc.put("city", "new york");
col.insert(doc);
BasicDBObject doc2 = new BasicDBObject();
doc2.put("name", "mirko");
doc2.put("age", 23);
doc2.put("city", "madrid");
col.insert(doc2);
BasicDBObject doc3 = new BasicDBObject();
doc3.put("name", "jon");
doc3.put("age", 34);
doc3.put("city", "unknown");
col.insert(doc3);
Its look so "long". To add only 3 Persons I have to create always a new BasicDBObject and insert it with the same line code (col.insert(bla))? It cant be ^^ And an other question too: At the first time(doc) im adding name, age and city as column. Why do I have to add "name", "age" and "city" again and again... I just want to add "mirko", 23 and "madrid" for doc2.
The last thing what bugs me is that I can add a new Dokument to the Collection with the same(!) values. I could add a new jon with 34 years and the same city. Is this ok? And if yes, I would like to change it. Howto?
Thank you!
Use json for it..
String json = "{'key' : 'value'}"; /* Create json formatted data here */
DBObject dbObject = (DBObject)JSON.parse(json);
collection.insert(dbObject);
No need to execute insert several times. You can make one insert call for collection of objects:
http://api.mongodb.org/java/2.0/com/mongodb/DBCollection.html#insert(java.util.List)
For example:
List<BasicDBObject> docs = new ArrayList<BasicDBObject>();
BasicDBObject doc = new BasicDBObject();
doc.put("name", "klaus");
doc.put("age", 30);
doc.put("city", "new york");
docs.add(doc);
BasicDBObject doc2 = new BasicDBObject();
doc2.put("name", "mirko");
doc2.put("age", 23);
doc2.put("city", "madrid");
docs.add(doc2);
BasicDBObject doc3 = new BasicDBObject();
doc3.put("name", "jon");
doc3.put("age", 34);
doc3.put("city", "unknown");
docs.add(doc3);
col.insert(docs);
You can always try Morphia,a java library, for MongoDB. It lets you save, retrieve and update POJO objects as documents.
For your second query related to collections with same values, in mongoDB you have the option to use unique indexes which makes sure no two records of same values are inserted in the collection