What is Java Mongo Criteria for the following request - java

I would like to use mongodb.core.query.Criteria for following request:
db.accounts.find({ "personalSettings.nickName" : "testNickName"})
My scheme of document is:
{
"_id" : ObjectId("5354de90ad9b0f6c60bef7ba"),
"personalSettings" : {
"avatar" : "http://127.0.0.1:8080/assets/samples/avatar.png",
"nickName" : "testNickName"
},
"userName" : "testUser#testDomain.com"
}
I've tried to use this:
Query query = new Query(Criteria.where("personalSettings.nickName").is("testNickName"));
but i got:
java.lang.IllegalArgumentException: [Assertion failed] - this argument is required; it must not be null
personalSettings is a Map of < String,String >
Thanks

#Override
public Account getAccountByNickName(String nickname, String accountsCollection) {
Criteria criteria = Criteria.where("personalSettings.nickName").is(nickname);
DBCollection coll = mongoOperation.getCollection(accountsCollection);
DBCursor dbCursor = coll.find(Query.query(criteria).getQueryObject());
DBObject dbobj = dbCursor.next();
Account account = (new Gson()).fromJson(dbobj.toString(), Account.class);
return account;
}
For now - only one way :)
Because MongoDB doesn't support searching in map by elemMatch and doesn't support searching by ongoTemplate/MongoOperation

Related

How to get only specific fields from Mongodb document?

From system.profile collection I have documents like this:
{
"op" : "command",
"ns" : "..",
"command" : {
"count" : "..",
"query" : {
"$and" : [
...
]
}
},
"responseLength" : 48,
"millis" : 18,
}
Some queries don't have the command field instead they have 'query' field. I want to check if 'command' field exist. If it does then append that to my Stringbuilder object, if not append 'query'.
UPDATE:
I have tried to use Projection as suggested by Davide by but still I am not finding a way to checking if query exist, if it does then append that.
DBCollection collection = mongoTemplate.getCollection("system.profile");
DBObject query = new BasicDBObject("command", new BasicDBObject("$exists",true));
BasicDBObject fields = new BasicDBObject("command",1).append("millis", 1).append("ts", 1);
DBCursor cursor = collection.find(query, fields);
while(cursor.hasNext()) {
sb.append(cursor.next());
sb.append(System.getProperty("line.separator"));
}
return sb;
}
You need to use the following method:
public DBCursor find(DBObject query, DBObject projection);
From java doc:
projection - specifies which fields MongoDB will return from the documents in the result set.

How to get rid of the mongo IDs when converting a collection to json

I'm using the mongo java API to convert a collection to json:
MongoCollection<Document> coll = db.getCollection("day_EURUSD");
FindIterable<Document> fi = coll.find();
System.out.println(fi.first().toJson());
However the outcome still contains nongoDB 'clutter':
{ "_id" : { "$oid" : "565d90808b821237efdc39cb" }, "currencyPairs" : [{ "a....
How can I elegently get rid of _id and $oid so that i'm back to a 'normal' json?
Thanks
Try this:
MongoCollection<Document> coll = db.getCollection("day_EURUSD");
FindIterable<Document> fi = coll.find();
fi.forEach(new Block<Document>() {
#Override
public void apply(final Document document) {
// Suppress the DB Id column of the query result.
document.remove("_id");
}
});
...

MongoDB $in with $and Query

Is this type of query possible?
I need to query the database for data for a specified date for a set of specified stocks. So the data needs to have "this" date and be one of "these" symbols.
I have the following code:
public void findDateStockSet(String date, ArrayList<String> symbolSet) throws UnknownHostException {
this.stocks = this.getCollectionFromDB();
BasicDBObject objectToFind = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("date", date));
obj.add(new BasicDBObject("symbol", new BasicDBObject("$in", symbolSet)));
objectToFind.put("$and", obj);
DBCursor cursor = this.stocks.find(objectToFind);
System.out.println("Finding Stocks");
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println();
}
This always comes up null. Can someone explain how to make a query like this work?
You don't need to use $and operator, just build the query as the json below:
{ "date" : "20100223", "symbol" : { $in : [ "appl", "goog" ] } }
I like to use BasicDBObjectBuilder util class to build DBObjects. So your query will be:
DBObject query = BasicDBObjectBuilder.start()
.add("date", date)
.push("symbol")
.add("$in", symbolSet)
.get();

how to get particular field from the result of full test search in monodb using java

I have some documents in my mongodb as follows
{"Filename":"PHP Book.pdf","Author":"John" ,"Description":"This is my PHP Book"}
{"Filename":"Java Book.html" ,"Author":"Paul" ,"Description":"This is my JAVA Book"}
{"Filename":".NET Book.doc" ,"Author":"James" ,"Description":"This is my .NET Book"}
I have created text index on Description field and below is my code which does full text search on Description field.
m = new Mongo("10.0.0.26", 27017);
DB db = m.getDB("soft") ;
DBCollection col = db.getCollection("pocnew") ;
String collection = col.toString();
DBObject searchCmd = new BasicDBObject();
searchCmd.put("text", collection);
searchCmd.put("search", "php");
CommandResult commandResult = db.command(searchCmd);
System.out.println(commandResult);
I am getting following result
{ "serverUsed" : "/10.0.0.26:27017" , "queryDebugString" : "php||||||" , "language" : "english" , "results" : [ { "score" : 0.5833333333333334 , "obj" : { "_id" : { "$oid" : "51cd7d302d45471420c1132b","Filename":"PHP Book.pdf","Author":"John" ,"Description":"This is my PHP Book"}]}}
My requirement is to display only filename field value i.e only PHP Book.pdf
please suggest me
Thanks
You may have to dig through the returned document to get to Filename
CommandResult commandResult = db.command(searchCmd);
BasicDBList results = (BasicDBList)commandResult.get("results");
for( Iterator< Object > it = results.iterator(); it.hasNext(); )
{
BasicDBObject result = (BasicDBObject) it.next();
BasicDBObject dbo = (BasicDBObject) result.get("obj");
System.out.println(dbo.getString("Filename"));
}
In addition, if you just need the Filename field, you may want to add project option in searchCmd to limit the number of fields returned in search results. See the following link for text command returned document details and project option.
http://docs.mongodb.org/manual/reference/command/text/

Java MongoDB Query

I have a structure like this in my database:
{
{
"document_id" : 35,
"transport" : ["car", "plane", "train", "boat"]
},
{
"document_id" : 36,
"transport" : ["car", "bike", "train"]
}
}
How would I do a search query to find a document/record with for example transport 'plane'?
Thanks for any help.
Steven
from MongoShell
db.find({transport:"plane"}) would do.
MongoDB will search the entire array to match the query in case the value is an array.
Using Java Driver.
Yous first get the Mongo collection
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
BasicDBObject dbo = new BasicDBObject();
dbo.append("transport", "plane");
DBCursor cur = collection.find(dbo);
while (cur.hasNext()) {
list.add(JSONHelper.toJSON(cur.next().toMap()));
}
To search for an array containing an element, you can just check for that element against the array.
So, just using: -
db.collection.find({transport:"plane"})
would give you what you want.
Here's the implementation in Java: -
BasicDBObject doc = new BasicDBObject("document_id", 35)
.append("transport", new String[] {"car", "plane"});
BasicDBObject doc2 = new BasicDBObject("document_id", 36)
.append("transport", new String[] {"car"});
coll.insert(doc);
coll.insert(doc2);
DBObject query = new BasicDBObject("transport", "plane");
DBCursor cursor = coll.find(query, new BasicDBObject("_id", 0));
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output : -
{ "document_id" : 35 , "transport" : [ "car" , "plane"]}
#Document(collection = "document")
public class Transport {
private ObjectId document_id;
private ArrayList transport;
}
//
   List<String> list = new ArrayList<String>();
        list.add("car");
        list.add("plane");
   list.add("train");
        list.add("boat");
Transport transport;
transport.setTransport(list);

Categories

Resources