MongoDb accesing nested documents in java - java

I am new to MongoDB. I am trying to access nested doc in mongodb. My sample doc is
{
"Advertisement" : {
"html" : "zxcxz"
},
"Notification" : {
"date_from" : ISODate("2013-06-30T18:30:00Z"),
"date_too" : ISODate("2013-07-16T18:30:00Z"),
"description" : "vcvc",
"url" : "vcvc"
},
"_id" : ObjectId("51e4f10ee4b08e0a6ebcbe46"),
"group_name" : "sumit",
"target_audience" : {
"gender" : "male",
"section" : "xyz",
"catagory" : "--Computer--",
"location" : {
"country" : "--Country--",
"state" : "--State--",
"city" : "--City--"
}
}
}
I am trying to get gender from target_audience. My java code is
DBCursor f=con.coll.find(query);
while(f.hasNext())
{
f.next();
gender=(String) f.curr().get("target_audience.gender");
}
But it returns null.

The result of DBCursor.next() and DBCursor.curr() is a BasicDBObject. For keys with embedded documents, BasicDBObject.get(key) returns a BasicDBObject
DBCursor f=con.coll.find(query);
while(f.hasNext())
{
BasicDBObject result = (BasicDBObject) f.next();
BasicDBObject target = (BasicDBObject) result.get("target_audience");
gender = (String) target.get("gender");
}

Related

Translate MongoDB Query to Java

I need to use this request in java using mongodb driver
db.product.update({"orders._id":ObjectId("59328d583c5179156cb9c241")},
{
$set:{
"orders.$.description":"ccc"
}
})
my object
{
"_id" : ObjectId("59328d543c5179156cb9c240"),
"fullName" : "aaa",
"orders" : [
{
"_id" : ObjectId("59328d583c5179156cb9c241"),
"description" : "bbb"
}
]
}
Result
{
"_id" : ObjectId("59328d543c5179156cb9c240"),
"fullName" : "aaa",
"orders" : [
{
"_id" : ObjectId("59328d583c5179156cb9c241"),
"description" : "ccc"
}
] }
what i have tried
BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("orders._id", myId));
set.append("$set", new BasicDBObject("description", "ccc");
product.update(searchQueryByOrderId, set);
driver used :
https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver

Count document MongoDB java

I am new to MongoDB and I am finding rather complicated to count the child number of my nested documents.
This is part of my 'users' collection.
"_id" : ObjectId("58f9f7a91fb2bf7c46abe5d6"),
"name" : "fernando guima",
"premium" : true,
"email" : "lolol#loladamix.com",
"creationDate" : ISODate("2017-04-21T12:14:33.970Z"),
"playlists" : [
{
"name" : "minha Playlist",
"creationDate" : ISODate("2017-04-21T12:14:33.982Z"),
"videos" : [
{
"video_id" : "video1",
"creationDate" : ISODate("2017-04-21T13:00:38.461Z")
},
{
"video_id" : "video2",
"creationDate" : ISODate("2017-04-21T13:00:38.502Z")
}
]
},
{
"name" : "minha Playlist 2",
"creationDate" : ISODate("2017-04-21T12:14:33.983Z"),
"videos" : [ ]
}
]
}
I want to be able to retrieve the number of 'videos' in my 'playlist' (playlist childs) and retrieve a video data, how can I do that?
I wrote the following code that adds a video to a given playlist:
public void addToPlaylist(String parameter, String value, String playListName, String video_id){
//user document
BasicDBObject query = new BasicDBObject(parameter, value);
//First it fetches the wanted document by a parameter and its value e.g, (name, Fernando)
BasicDBObject mObject = new BasicDBObject();
mObject.put("video_id", video_id);
mObject.put("creationDate", new Date());
BasicDBObject updateObj = new BasicDBObject();
//falta percorrer o array das playlists para encontrar o id pelo nome da playlist
updateObj.put("$push", new BasicDBObject("playlists."+"0"+".videos", mObject));
mMongo.getCollection("users").updateOne(query, updateObj);
}
I expect to receive, {videos : 2} as the number of videos in my first playlist. And some output about video data like: {"video_id" : "video1"}
Regards
You can use below query. The query will $match to select the document followed by $unwind of playlists array and $project to reach videos array to calculate its $size and extract video_id.
MongoClient client = new MongoClient("localhost", 27017);
MongoDatabase database = client.getDatabase("db");
MongoCollection<Document> collection = database
.getCollection("collection");
Bson filter = Filters.eq("_id", new ObjectId("58f9f7a91fb2bf7c46abe5d6"));
List<VideoResult> results = collection.aggregate(Arrays.asList(Aggregates.match(filter), Aggregates.unwind("$playlists"), Aggregates.project(Projections.fields(Arrays.asList(Projections.computed("videos", new Document("$size","$playlists.videos")),
Projections.computed("video_ids", "$playlists.videos.video_id")))))).map(VideoResult::new).into(new ArrayList<>());
Output:
{
"_id" : ObjectId("58f9f7a91fb2bf7c46abe5d6"),
"videos" : 2,
"video_ids" : [
"video1",
"video2"
]
}
{
"_id" : ObjectId("58f9f7a91fb2bf7c46abe5d6"),
"videos" : 0,
"video_ids" : [ ]
}
Pojo:
public class VideoResult {
private int videos;
private List<String> videoIds;
public VideoResult(Document doc) {
this.videos = doc.getInteger("videos");
this.videoIds = (List<String>) doc.get("video_ids");
}
// getters and setters
}
Another solution, MongoDB 3.4
db.users.aggregate([
{$unwind: '$playlists'}, {$addFields: {'playlists.id': '$_id'}},
{$replaceRoot: {newRoot: '$playlists'}},
{$unwind: {path: '$videos', preserveNullAndEmptyArrays: true}},
{$group: {_id: {name: '$name', creationDate: '$creationDate', _id: '$id'},
video_ids: {$push: '$videos.video_id'},
videos: {$sum: {$cond: [{$ifNull: ['$videos', 0]}, 1, 0]}}}},
{$addFields: {_id: '$_id._id'}}])
Output:
{
"_id" : ObjectId("58f9f7a91fb2bf7c46abe5d6"),
"video_ids" : [ ],
"videos" : 0
}
{
"_id" : ObjectId("58f9f7a91fb2bf7c46abe5d6"),
"video_ids" : [
"video1",
"video2"
],
"videos" : 2
}

How to get specific values of an embedded document Array in MongoDB using Java Driver

what I tried to is getting all sitename from every embedded documents in the array.I have tried using following syntax but didn't work
( sites.$.site )
{
"user" : "username",
"sites" : [{
"sitename" : "site.com",
"url" : "site.com",
}, {
"sitename" : "site2.com",
"url" : "site2.com",
},{
"sitename" : "site2.com",
"url" : "site2.com",
}]
}
Mongo-java,
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase database = mongoClient.getDatabase("Test");
MongoCollection<Document> collection = database.getCollection("collection");
ArrayList<Document> doc = new ArrayList<Document>();
doc.add(new Document().append("$unwind","$sites"));
doc.add(new Document().append("$project",new Document().append("sitename","$sites.sitename")));
List<Document> results =collection.aggregate(doc).into(new ArrayList<Document>());
for(Document res: results){
System.out.println(res.toJson());
}
output:
{ "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site.com" }
{ "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site2.com" }
{ "_id" : { "$oid" : "58c26ce044400b08ca6ff483" }, "sitename" : "site2.com" }

MongoDB Query in Array of Arrays and add if not present

I have
{
"Districts" :
[{ "name" : "Krishna"
, "Locations" : [{ "name" : "Vijayawada"}
,{ "name" : "Machilipatnam"}]}
, { "name" : "Guntur"
, "Locations" : [{ "name" : "Satenpalli"}]}
]
, "_id" : 1
, "name" : "Andhra Pradesh"
}
I am trying to create one more Location "Achampet" if District name is "Guntur" so the result should be this below. The result should be the same even if I try to add Achampet more than once.
{
"Districts" :
[{ "name" : "Krishna"
, "Locations" : [{ "name" : "Vijayawada"}
,{ "name" : "Machilipatnam"}]}
, { "name" : "Guntur"
, "Locations" : [{ "name" : "Satenpalli"}
,{ "name" : "Achampet"}]}
]
, "_id" : 1
, "name" : "Andhra Pradesh"
}
But my java code doesn't work
DBObject newLoc = new BasicDBObject("Districts", new BasicDBObject("name", distName).append("Locations", new BasicDBObject("name", locName)));
if (statesColl.findOne(newLoc) == null) {
DBObject updateLoc = new BasicDBObject("$push", newLoc);
statesColl.update(queryDist, updateLoc);
}
It is creating a new District everytime I try to add a location. How can I fix this?
This is how you can do it using the $ positional operator in Java:
...
DBObject selectQuery = new BasicDBObject("_id", 1); // Matches the document
selectQuery.append("Districts.name", distName); // Matches the element in the array where District name = Guntur
BasicDBObject updateFields = new BasicDBObject();
updateFields.put("Districts.$.Locations", new BasicDBObject("name":"Achampet"));
DBObject updateQuery = new BasicDBObject("$addToSet", updateFields);
statesColl.update(selectQuery, updateQuery);
...

How to retrieve a value from mongoDB, by its key name?

I am new to mongoDB. I am using java and mongoDB. I have a json like,
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "AA" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "AA" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "BB" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
[{ "_id" : { "$oid" : "4ceb753a70fdf877ef5113ca"} , "HomeTown" : "BB" ,
"PhoneNumber" : { "CustName" : "xxx" , "Number" : "3403290"},
"MobileNumber" : { "CustName" : "yyy" , "Number" : "9323304302"}}]
In a collection all doc's have different HomeTown, i just know the key name HomeTown, how can i get the HomeTown values?
In mongo site, i just can find find() and findOne().
Thanks!
find() is enough.
db.CollectionName.find({},{HomeTown:1})
in java, it would be:
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
field.put("HomeTown", 1);
DBCursor cursor = db.getCollection(collectionName).find(query,field);
while (cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
result.add(obj.getString("HomeTown"));
}
db.CollectionName.find({},{HomeTown:1,PhoneNumber:0})
Would be wrong, but
db.CollectionName.find({},{HomeTown:1, _id:0})
would be right, because you need to suppress _id explicitly. Just FYI.
Mongo m = new Mongo('localhost',27017);
DB db = m.getDB("yourDBName");
Collection coll = db.getCollection("yourCollectionName")
BasicDBObject query = new BasicDBObject();
query.put("HomeTown", 1);
DBCursor cursor = coll.find(query);
ArrayList arr = new ArrayList();
String str;
while (cursor.hasNext()) {
str=cursor.curr().get("HomeTown").toString();
arr.add(str);
}
for(int value=0;value<=10;value++)
{
DBCollection tableDetails = db.getCollection("Collection Name");
BasicDBObject queryDetails = new BasicDBObject();
queryDetails.put("_id", value);
DBCursor cursorDetails =tableDetails.find(queryDetails);
DBObject oneDetails;
boolean Name=cursorDetails.hasNext();
while(Name)
{
oneDetails=cursorDetails.next();
String data=oneDetails.get("HomeTown").toString();
System.out.println(data);
}
}

Categories

Resources