I want to define a document in MongoDB in order to keep a list of key-value pairs in addition to some more information . I need to query on keys and extract just values , not whole the document. Let’s say it looks like:
{ title :” Do not stop me now”
Artist: “Queen”
Info :{
Metadata: [
{key: “genre”, value: “Rock” },
{key: “bps”, value: 120}
]
}
}
I selected this format based on http://java.dzone.com/articles/indexing-schemaless-documents
I want to query like select “genre” from song where artist is “Queen”
My current code is:
BasicDBObject eleMatch = new BasicDBObject();
eleMatch.put("key","genre");
BasicDBObject up = new BasicDBObject();
up.put("$elemMatch",eleMatch);
BasicDBObject query = new BasicDBObject();
query.put("info.Metadata", up);
query.put(“Artist”,”Queen”);
BasicDBObject fields = new BasicDBObject("info.Metadata.$",1).append("_id", false);
DBObject object =collection.findOne(query,fields);
I tried to extract value like:
System.out.println( (((BasicBSONList) ((BasicBSONObject) object.get("info")).get("Metadata")).get("value")).toString());
But I cannot get access to "value"
How I can solve it?
The positional operator return an array of one element. So, what you are converting to string is an array and of course you will get a kind of java id.
Cast it to array and get its first element
Related
I have a mongo collection with objects like these:
[
{
"_id" : "a2d",
"entityType" : "Location",
"type" : "STRING",
},
{
"_id" : "a1_order",
"entityType" : "Order",
"type" : "STRING",
}
]
Trying to append the _entityType to all document's id where it is not present at the end id the id (the first object in the above case).
Using mongo with Spring, but I'm already stuck with the first step, to get all the objects with no entityType in id.
Thinking about something like this, with regex, but I'm not sure how should it look like:
Query query = new Query();
query.addCriteria( Criteria.where( "id" ).regex( "here i need the entity type of the current document" ) );
You can build your regex by '^' ('starts with' Regex).
So you need a function who point in all documents and check this filter
List<Document> result = new ArrayList<Document>();
StringBuilder idPrefix = new StringBuilder();
idPrefix.append("^");
idPrefix.append(idCode);
idPrefix.append("_");
List<Bson> filters = new ArrayList<Bson>();
filters.add(Filters.regex("_id", keyPrefix.toString()));
for (Document d : yourCollections.find(Filters.and(filters)))
list.add(d);
You actually want a "reverse regex" here, as you need to use the data in the document in order to match on another field.
Presently you can really only do this with MongoDB using $where, which evaluates JavaScript on the server. So for spring mongo, you need the BasicQuery instead, so we can construct from BasicDBObject and Code primatives:
BasicDBObject basicDBObject = new BasicDBObject("$where",
new Code("!RegExp('_' + this.entityType + '$','i').test(this.id)"));
BasicQuery query = new BasicQuery(basicDBObject);
That will test the "id" field in the document to see if it matches the value from entityType at the "end of the string" and without considering "case". The ! is a Not condition, so the "reverse" of the logic is applied to "not match" where the field actually did end that way.
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));
I trying to perform a query in my mongo database using java code. I want to filter the result of the query using cursor. Basically I want to filter the cursor results two times. My query return some documents, and I want to filter them based on a field of document and a sub-field of the first field. For example:
DBCursor cursor = coll.find(query);
while(cursor.hasNext()) {
BasicDBObject obj = (BasicDBObject) cursor.next();
System.out.println(obj.getString("images"));
}
Return the image field from all quered documents. What should I do if I want to return the field "link" which is a subfield of field "images"? I tried obj.getString("images").getString("link"), however it doesn't work. Images is an array with three fields the first one is the filed "link". When the above return is the following: [ { "link" : "http://distilleryimage1.ak.instagram.com/fc7c5_7.jpg" , "phash" : "01000010101000101010111101" , "persons" : 1}] . I want to return just the first field link.
Just get images as ArrayList:
ArrayList<BasicDBObject> images = (ArrayList<BasicDBObject>)obj.get("images");
for(BasicDBObject image: images)
{
String link = image.getString("link");
.......
}
I have a JSON in MongoDB with the following structure:
{
id:"_234234",
"stationId":"ALM",
"storageData": {
}
}
To retrieve JSON with storageData equal to null, in MongoDB I query as:
db.collection.find({"storageData":{"$gt" : {}}})
It gives me list of JSON bodies with empty storageData. So how do I represent that in Java
BasicDBObject obj=new BasicDDBObject("storageData", new BasicDBObject("$gt",{}));
collection.find(obj);
I am getting an error near BasicDBObject("$gt",{}))...
How do I represent ("$gt",{}) in Java??
First understand that null is a valid value. This would be valid:
{
id:"_234234",
StationId:"ALM",
StorageData: null
}
and retrieving the document, asking for storagedata which is null would retrieve the doc with the id _234234.
If what you need is to check which documents DON'T have the key "storagedata" then use the $exist keyword or construct the query in this way:
db.yourcollection.find("this.storagedata == null")
I would do it via query, and not in Java because it would alleviate cpu time and memory.
All you want to to here is represent an empty object:
BasicDBObject query = new BasicDBObject(
"storageData", new BasicDBObject(
"$gt",new BasicDBObject()
)
);
Which of course produces the query:
{ "storageData" : { "$gt" : { } } }
So that's it, just call BasicDBObject without any arguments.
How to convert hql query result directly to Json.I tried this one
Query query=session.createQuery(SQLUtilsConstants.fQuery);
query.setParameter(StringConstants.TRPID, trId);
List list=query.list();
gson = new Gson();
String jsonStudents = gson.toJson(list);
System.out.println("jsonStudents = " + jsonStudents);
When i converted.I get a json with list of values without properties.Query result contains data from multiple table .I want to generate result with properties as key and value as output.If query contains customerid and customername then i need a result like this.
[{"customerid" : "abc", "customername" : "rose"}]
But using above code i getting like this..
[{"abc", "rose"}]
How can i do this???
You should create a Map, how ever you want it. then parse the map into json.
Map<String,WhatEver> newMap = new HashMap<String,WhatEver>();
foreach(WhatEver item: list){
//create your map how ever you like it to be
}
String jsonStudents = gson.toJson(newMap);