I have a following document
{
"_index" : "Testdb",
"_type" : "artWork",
"_id" : "0",
"_version" : 1,
"found" : true,
"_source":{"uuid":0,"ArtShare":{"TotalArtShares":0,"pricePerShare":0,"ArtworkUuid":12,"AvailableShares":0,"SoldShares":0},"StatusHistoryList":[{"ArtWorkDate":"2015-08-26T13:20:17.725+05:00","ArtworkStatus":"ACTIVE"}]}
}
i want to access/retrieve the value of ArtShare and its attributes and values of array StatusHistoryList
i am doing like this
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
)
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
//how to fetch `artShare` whole nested document and array elements `StatusHistoryListof`
}
UPDATE
if i do this
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
,"_source","ArtShare.TotalArtShares")
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
var totalShares= get.getField("ArtShare.TotalArtShares").getValue.toString().toInt
}
then following exception thrown
org.elasticsearch.ElasticsearchIllegalArgumentException: field [ArtShare] isn't a leaf field
at org.elasticsearch.index.get.ShardGetService.innerGetLoadFromStoredFields(ShardGetService.java:368)
at org.elasticsearch.index.get.ShardGetService.innerGet(ShardGetService.java:210)
at org.elasticsearch.index.get.ShardGetService.get(ShardGetService.java:104)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:104)
at org.elasticsearch.action.get.TransportGetAction.shardOperation(TransportGetAction.java:44)
at org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction$ShardTransportHandler.messageReceived(TransportShardSingleOperationAction.java:297)
at org.elasticsearch.action.support.single.shard.TransportShardSingleOperationAction$ShardTransportHandler.messageReceived(TransportShardSingleOperationAction.java:280)
at org.elasticsearch.transport.netty.MessageChannelHandler$RequestHandler.doRun(MessageChannelHandler.java:279)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:36)
please guide me how to fetch these values
Yeah Actually the problem is that you have mentioned both "ArtShare" and "ArtShare.TotalArtShares" in the fields array. So it throws exception as you have already retrieved complete ArtShare object.
So please mention the fields that you want, If you want specified nested values then no need to access complete parent object.
Try this:
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","StatusHistoryList",
"ArtShare.TotalArtShares")
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
var totalShares= get.getField("ArtShare.TotalArtShares"
}
And if you want complete "ArtShare" object then simply write :
val get=client.prepareGet("Testdb","artWork",Id.toString())
.setOperationThreaded(false)
.setFields("uuid","ArtShare","StatusHistoryList"
)
.execute()
.actionGet()
if(get.isExists())
{
uuid=get.getField("uuid").getValue.toString().toInt
//how to fetch `artShare` whole nested document and array elements `StatusHistoryListof`
}
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 have the following code, :
CommandResult cr = db.doEval("db." + collectionName + ".aggregate("
+ query + ")");
Command result is giving in batches, where I need to get in single value.
Batch Result:{ "serverUsed" : "/servername" , "retval" : { **"_firstBatch**" : [ { "visitor_localdate" : 1367260200} , { "visitor_localdate"
Expected Result:
{ "serverUsed" : "/servername" , "retval" : { "**result**" : [ { "visitor_localdate" : 1367260200} , { "visitor_localdate"
The Mongo DB we are using is 2.6.4 with 64 bit.
Can any one help with this?. I am guessing there is some Configuration issue.
Your doing this all wrong. You don't need to jump through hoops like this just to get a dynamic collection name. Just use this syntax instead:
var collectionName = "collection";
var cursor = db[collectionName].aggregate( pipeline )
Where pipeline also is just the array of pipeline stage documents, ie:
var pipeline = [{ "$match": { } }, { "$group": { "_id": "$field" } }];
At any rate the .aggregate() method returns a cursor, you can iterate the results with standard methods:
while ( cursor.hasNext() ) {
var doc = cursor.next();
// do something with doc
}
But you are actually doing this in Java and not JavaScript, so from the base driver with a connection on object db you just do this:
DBObject match = new BasicDBObject("$match", new BasicDBObject());
DBObject group = new BasicDBObject("$group", new BasicDBObject());
List pipeline = new ArrayList();
pipeline.add(match);
pipeline.add(group);
AggregationOutput output = db.getCollection("collectionName").aggregate(pipeline);
The pipeline is basically a list interface of DBObject information where you construct the BSON documents representing the operations required.
The result here is of AggregationOutput, but cursor like results are obtainable by additionally supplying AggregationOptions as an additional option to pipeline
There was something related to bacth added in mongodb 2.6, more details here: http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/#example-aggregate-method-initial-batch-size
From the link
db.orders.aggregate(
[
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 2 }
],
{
cursor: { batchSize: 0 }
}
)
You might be having a cursor batch in your aggregate query
The answer from Neil Lunn is not wrong but I want to add that the result you were expecting is a result for mongodb versions earlier than v2.6.
Before v2.6, the aggregate function returned just one document containing a result field, which holds an array of documents returned by the pipeline, and an ok field, which holds the value 1, indicating success.
However, from mongodb v2.6 on, the aggregate function returns a cursor (if $out option was not used).
See examples in mongodb v2.6 documentation and compare how it worked before v2.6 (i.e. in v2.4):
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 insert a document in MongoDB by using Java:
BasicDBObject document = new BasicDBObject();
document.put("Atmospheric_Pressure", Atmospheric_Pressure);
document.put("Humidity", Humidity);
collection.insert(document);
System.out.println(document);
The insert is working, I checked into the collection and it was ok. The System.out gave me the follwing result:
{ "Atmospheric_Pressure" : "3" , "Humidity" : "3" , "_id" : { "$oid" : "539d964070d2dfc425fc06a0"}}
My question is how can I get only the ID? I need only the value of the third item.
Thank you in advance.
You can get it by calling document.getObjectId("_id").
This will return you an object of type ObjectId. If you just want to have the string value, you can proceed by calling toString() on the returned object ID.
var schedule = [];
var data = {
'user_id' : '12',
'day_of_week' : 'Monday',
'when' : 'start',
'modified' : 'true'
}
schedule.push(data);
var data = {
'user_id' : '13',
'day_of_week' : 'Tuesday',
'when' : 'end',
'modified' : 'false'
}
schedule.push(data);
// schedule would have two objects in it
I am posting array to servlet using jquery ajax post request as below .
data : {'myData':schedule},
url :"./myController",
Now how can I get array of objects and literate to get all the values? Each array object has string, long and boolean type values. How can I get all the values by iterating?
May be you can try this
json.getJSONObject("myData").getString("your_values");