(MongoDB Java) $push into array - java

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));

Related

how to search the array with no empty value from mongodb in java?

I would like to get the data tags from mongodb whose data is not null
"tags" : [ ]
I tried doing $ne but no chance.
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("tags", new BasicDBObject("$ne", []));
Any help would be appreciated.
I solved this by using this query
searchQuery.put("tags.1", new BasicDBObject("$exists", true));

How to use $in operator in mongodb with two fields in java

I would like to retrieve the following information:
select names from database where address like 'colombo' and age>20;
but for MongoDB in Java. Essentially, it should return all names that contain the word colombo ang age greater than 20 in them. I know that there is the $in operator in MongoDB, but how do I do the same in Java, using the Java driver? I've been trying to look for it everywhere but am getting nothing. I've tried:
query = new BasicDBObject("names", new BasicDBObject("$in", "colombo"), new BasicDBObject("age", "$gt20"));
But it didn't worked :( Please help!
Try this
BasicDBObject query = new BasicDBObject("names", new BasicDBObject("$in", Arrays.asList("colombo")));
query.append("age", new BasicDBObject("$gt", 20));
FindIterable<Document> find = collection.find(query);
MongoCursor<Document> iterator = find.iterator();
Document doc = null;
while (iterator.hasNext()) {
doc = iterator.next();
System.out.println(doc);
}
The $in operator will not be suitable for such as you can only use it to match values that are in an array or to search for documents where the value of a field equals any value in a specified array.
In your case you need a $regex operator to fulfil the query by performing a SQL LIKE operation:
db.collection.find({
"names": { "$regex": /colombo/, "$options": "i" },
"age": { "$gt": 20 }
})
or
db.collection.find({
"names": /colombo/i },
"age": { "$gt": 20 }
})
which can be implemented in Java as
Pattern pattern = Pattern.compile("colombo", Pattern.CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("names", pattern)
.append("$age", new BasicDBObject("$gt", 20));
DBCursor result = coll.find(query);
If using the 3.0.x and newer drivers:
Document regx = new Document();
regx.append("$regex", "(?)" + Pattern.quote("colombo"));
regx.append("$options", "i");
Document query = new Document("names", regx).append("$age", new Document("$gt", 20));
FindIterable<Document> iterable = db.getCollection("coll").find(query);

How to search a document and remove field from it in mongodb using java?

I have a device collection.
{
"_id" : "10-100-5675234",
"_type" : "Device",
"alias" : "new Alias name",
"claimCode" : "FG755DF8N",
"hardwareId" : "SERAIL02",
"isClaimed" : "true",
"model" : "VMB3010",
"userId" : "5514f428c7b93d48007ac6fd"
}
I want to search document by _id and then update it after removing a field userId from the result document. I am trying different ways but none of them is working. Please help me.
You can remove a field using $unset with mongo-java driver in this way:
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("testDB");
DBCollection collection = db.getCollection("collection");
DBObject query = new BasicDBObject("_id", "10-100-5675234");
DBObject update = new BasicDBObject();
update.put("$unset", new BasicDBObject("userId",""));
WriteResult result = collection.update(query, update);
mongo.close();
The easiest way is to use the functionality in the java driver:
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(new ObjectId("10-100-5675234")));
Update update = new Update();
update.unset("userId"); //the fields you want to remove
update.set("putInYourFieldHere", "putInYourValueHere"); //the fields you want to add
mongoTemplate.updateFirst(query, update, Device.class);
The above code assumes that your "_id" is your mongodb normal "_id" which means that the variable you are looking for must be encased in the new ObjectId().
Long time since this post was opened, but might be useful for someone in the future.
device.updateMany(eq("_id", "whatever"), unset("userId"));
An ugly way is to replace the old version with the new version of you document (no userid).
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("_type", "Device");
newDocument.put("alias", "new Alias name");
// ...
BasicDBObject searchQuery = new BasicDBObject().append("_id", "10-100-5675234");
collection.update(searchQuery, newDocument);
The MongoDB documentation provides a clear answer to this question: use the $unset update operator.

MongoDb Polygon Search Query returns no result

I have problems regarding a Polygone Search in my MongoDB.
I have a document structure like:
Object:{id,type,...,
data:{
name,
loc:{
lng:xxx
lat:yyy
type:Point}}}
I have an 2d Index on "data.loc".
My query in java code is:
DBCollection coll = database.getCollection(type);
BasicDBList points = new BasicDBList();
points.add(bbox.getNe());
points.add(bbox.getSe());
points.add(bbox.getSw());
points.add(bbox.getNw());
points.add(bbox.getNe());
BasicDBList parentList = new BasicDBList();
parentList.add(points);
DBObject query = new BasicDBObject("data.loc",
new BasicDBObject("$geoWithin",
new BasicDBObject("$geometry", new BasicDBObject("type","Polygon")
.append("coordinates", parentList))));
The Debuger tells me that the query is for example
{ "data.loc" : { "$geoWithin" : { "$geometry" : { "type" : "Polygon" ,
"coordinates" : [ [ [ 48.240553 , 16.451597] , [ 48.162751 ,
16.451597] , [ 48.162751 , 16.303968] , [ 48.240553 , 16.303968] , [ 48.240553 , 16.451597]]]}}}}
But after typing
DBCursor cursor = coll.find(query);
try {
while(cursor.hasNext()) {
data.add(cursor.next().get("data"));
}
} finally {
cursor.close();
}
return data;ยด
data is allways null.
Can anyone find any problems in my approach or does maybe someone have a better approach? In fact I want to do a boundingbox search on my database.
Thank you for your help!
Best regards
Daniel
Okay, so the Java MongoDB driver query for the points in the polygone for a GeoJson strcuture like this is
BasicDBList points = new BasicDBList();
points.add(bbox.getNe());
points.add(bbox.getSe());
points.add(bbox.getSw());
points.add(bbox.getNw());
points.add(bbox.getNe());
BasicDBList parentList = new BasicDBList();
parentList.add(points);
Set<Object> data = new CopyOnWriteArraySet<Object>();
DBObject query = new BasicDBObject("geometry",
new BasicDBObject("$geoWithin",
new BasicDBObject("$geometry", new BasicDBObject("type","Polygon")
.append("coordinates", parentList))));
System.err.println(query);

How to use aggregation in Mongo db Java driver with $match and $in?

How to convert below query into Java code for Mongo Java driver?
db.post.aggregate(
[
{ $match : {"name" :{'$in': ["michael", "jordan"] } }},
{ $group : { _id : "$game.id" , count : { $sum : 1 } } }
]
)
My function is not working:
DBObject match = new BasicDBObject('$match', new BasicDBObject("name", names));
The $in operator takes and array or list of arguments, so any list will basically do. But you need to form the corresponding BSON. Indenting your code helps to visualize:
BasicDBList inArgs = new BasicDBList();
inArgs.add("michael");
inArgs.add("jordan");
DBObject match = new BasicDBObject("$match",
new BasicDBObject("name",
new BasicDBObject("$in", inArgs )
)
);
DBObject group = new BasicDBObject("$group",
new BasicDBObject("_id","$game.id").append(
"count", new BasicDBObject("$sum",1)
)
);
According to the Aggregation Documentation, your query should look like:
DBObject match = new BasicDBObject('$match', new BasicDBObject('name', new BasicDBObject('$in', names)));

Categories

Resources