I have a collection like the one below, I want to get the _id value from the offerObject subdocument, I am using mongoTemplate in the Spring framework.
{
"_id" : ObjectId("543be5f3cbdf2e1eb442cb81"),`
"_class" : "com.mongodb.BasicDBObject",
"offerObject" : {
"_id" : ObjectId("543bbb7ecbdf85c6ceb44f33"),
"type" : "offer"
}
}
Can somebody help me with this?
I haven't used MongoTemplate, but based off previous experience doing java programming with Mongo, it would look something like this:
// Pull a document from the Collection
MongoDummyObject mdo = yourTemplate.findOne(query, MongDummyObject.class);
// Get the offer Object from the MongoDummyObject
OfferObject offerObject = mdo.getOfferObject();
// Pull the id from the offer object
String id = offerObject.getId();
Related
I'm trying to get the order number where a transactionId is equal to another variable I have in my code. My tolls.booths collection looks like this
In my code,
def boothsException = booths.find([ "pings.loc.transactionId": tollEvent.id, "pings.loc.order":1] as BasicDBObject).iterator()
println boothsException
I am getting boothsException = DBCursor{collection=DBCollection{database=DB{name='tolls'}
I would like to essentially say get where transactionId = 410527376 and give me that order number in boothsException (5233423).
This is using MongoDB Java Driver v3.12.2.
The code extracts the value from the returned cursor. I am using newer APIs, so you will find some differences in class names.
int transId = 410527376; // same as tollEvent.id
MongoCursor<Document> cursor = collection
.find(eq("pings.loc.transactionId", transId))
.projection(fields(elemMatch("pings.loc.transactionId"), excludeId()))
.iterator();
while (cursor.hasNext()) {
Document doc = cursor.next();
List<Document> pings = doc.get("pings", List.class);
Integer order = pings.get(0).getEmbedded(Arrays.asList("loc","order"), Double.class).intValue();
System.out.println(order.toString()); // prints 5233423
}
NOTES:
The query with projection gets the following one sub-document from the pings array:
"pings" : [
{
"upvote" : 575,
"loc" : {
"type" : "2dsphere",
"coordinates" : [ .... ],
"transactionId" : 410527376,
"order" : 5233423
},
...
}
]
The remaining code with looping the cursor is to extract the order value from it.
The following are the imports used with the find method's filter and projection:
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
I would like to retrieve the following information:
delete from database where name = 'AAA' and age>20;
but for MongoDB in Java. Essentially, it should delete the document that contain the word AAA and 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("age", new BasicDBObject("$gt", "20"), new BasicDBObject("name", "AAA"));
JSON which i want to delete is like this.
{"school" : "NewSchool" , "name" : "AAA" , "age" : "50"}
What you want is the find-term:
{
"name" : "AAA",
"age" : { $gt : 20 }
}
Construct this as your basic DB object, or simply use the new 3.x Filters to create the Bson for you. (As I personally only use 3.x, here's the appropriate example):
MongoClient client = ...
MongoDatabase db = client.getDatabase(...);
MongoCollection<Document> coll = db.getCollection(...);
coll.deleteMany(Filters.and(Filters.eq("name", "AAA"), Filters.gt("age", 20)));
Im trying to do a query to get all the values from my DB wich each have a date. One example:
leadTime: [
{
date: ISODate("2014-03-19T23:00:00Z"),
value: 25.8
},
{
date: ISODate("2014-03-20T23:00:00Z"),
value: 31.299999999999997
},
{
date: ISODate("2014-03-21T23:00:00Z"),
value: 34.4
}
]
enter code here
My code is:
DBObject query=new BasicDBObject("group",group);
DBObject serieData= col.findOne(query,new BasicDBObject(serie, 1));
if (serieData != null) {
List<DBObject> data = (List<DBObject>) serieData.get(serie);
for (DBObject item : data) {
result.add(new HistoryData((Date) item.get("date"),(Double) item.get("value")));
}
Now I want to get the values that the date is bigger than a date that I pass by parameter. The query I did is this:
DBObject query=new BasicDBObject("group",group)
.append("date", new BasicDBObject("$gte", parameterDate))
;
But I always receive the result empty, can you help me? sorry for my english and than
Assuming that leadTime is a field in your documents, your query has to look like this
DBObject query=new BasicDBObject("group",group)
.append("leadTime.date", new BasicDBObject("$gte", parameterDate))
;
The way you did it, MongoDB would have searched for a date field in your document root:
{ _id: "Foo",
date: ISODate("2014-03-19T23:00:00Z"),
[...]
}
Queries in MongoDB don't make a difference if the queried field is a single value or an array, so using the dot notation on a field which holds an array of subdocuments is perfectly valid.
What you want to do is not possible with a simple query.
But if you still want to do it in mongodb you need to use the aggregation framework, with something like that :
db.<col_name>.aggregate( [ { $unwind : "$group" }, { $match : {'group.date': { $gte : parameterDate } } ] )
this a js command, but you should be able to translate it easly in Java Driver (you can also add a $project operation to just return needed fields).
I am using Java and R to fetch data from my database and implement prediction. My json in mongodb is like:
{
"Server" : [
{
"deviceName" : "NEWSCVMM",
"availability" : 100,
"osVersion" : "6.3.9600",
"averageResponseTime" : 0.422,
"useswapmemory" : "983040",
"freeswapmemory" : "983040",
"model" : "Virtual Machine",
"numberOfCpu" : "1",
"vendor" : "Microsoft Corporation",
"vmList" : [ ],
"macadd" : [ ],
"cpuInfo" : "Intel(R) Xeon(R) CPU X5670 # 2.93GHz",
"memory" : "6188596",
"serialNo" : "00252-00000-00000-AA228",
"cpuUtilization" : 0,
}]
}
I want to access cpuUtilization from that json. I tried to access nested values using (.) but get result as NULL. I also tried to execute same on R shell but get result as NULL.
Here is what I have tried so far:
c.eval("query <- dbGetQuery(db,' mycollection','{\"hostId\":\"0.0.0.0\",\"windowsServer.cpuUtilization\":{\"$ne\":\"null\"},\"runtimeMillis\":{\"$ne\":\"null\"}}')");
c.eval("date <- query$runtimeMillis");
c.eval("host_id <- query$hostId");
c.eval("cpu <- query$Server.cpuUtilization");
c.eval("all_data<-data.frame(cpu,date)");
c.eval("training<- all_data");
c.eval("rf_fit<-randomForest(cpu~date,data=training,ntree=500)");
c.eval("new <- data.frame(date="+my_predicted_date+ ")");
c.eval("predictions<-predict(rf_fit,newdata=new)");
REXP memory_predictions= c.eval("predictions");
How do I access nested elements on either R shell or using java?
Dot notation should work in Java, I have been using it for quite a while now.
Check your code carefully, there might be a slight mistake somewhere.
Can you please post a part of your code here? I can then take a look and comment.
Here is what I normally do -
Lets say my document is like this -
{_id:0, start : {x:10, y:50}, end : {x:20, y:100}}
{_id:1, start : {x:20, y:50}, end : {x:30, y:100}}
{_id:2, start : {x:30, y:50}, end : {x:40, y:100}}
If I want to query based on "x" value in start field, I would write something like this:
MongoClient client = new MongoClient();
DB db = client.getDB("YourDBNAME");
DBCollection collection = db.getCollection("YOURCOLLECTIONAME");
QueryBuilder builder = QueryBuilder().start("start.x").greaterThan("20");
DBCursor cur = collection.find(builder.get());
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
Compare this code snippet with yours and see. You should get it working fine.
Let me know if this helps or you need more help on this.
How do I search through mongodb documents where documents have nested documents. For example I have a collection of private messages. Each private message has two nested documents - one representing the sending user and the other representing the receiving use. Both nested documents have the form -
userID: 34343,
name: Joe Bloggs
I would like to be able to search for all mail messages sent by a user (e.g. search the sender user nested document).
I am using the java driver. Do I need to create a DBObject which represents the nested document?
Thanks
As i understand u have document structure like this:
{
"someProperty" : 1,
"sendingUser" : {
userID : 34343,
name : "Joe Bloggs"
},
"recivingUser" : {
userID : 34345,
name : "Joe Bloggs"
}
}
So if you need find sending user with userID = 34345 you just need do following(i just think that is so, because actually i am working with c# driver for mongo):
DBCollection coll = db.getCollection("privateMessages")
query = new BasicDBObject();
query.put("sendingUser.userID", new BasicDBObject("$eq", 34345));
cur = coll.find(query); // all documents with sendingUser.userID = 34345 will be //returned by cursor
Also check tutorial for java driver
For MongoDB Java Driver v3.2.2. You can do something like this:
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.userID\": \"34343\"}"));
FindIterable<Document> iterable = collection.find(Document.parse("{\"sendingUser.name\": \"Joe Bloggs\"}"));
You can put the $eq inside the JSON style query string. Like { <field>: { $eq: <value> } }.