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();
Related
Suppose we have the following documents in a MongoDB collection:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
And the MongoDB query is
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
Can someone tell me how to write it in Java?
I am using:
List<BasicDBObject> obj = new ArrayList<>();
obj1.add(new BasicDBObject("shapes.color", "red"));
List<BasicDBObject> obj1 = new ArrayList<>();
obj2.add(new BasicDBObject("shapes.$", "1"));
BasicDBObject parameters1 = new BasicDBObject();
parameters1.put("$and", obj1);
DBCursor cursor = table.find(parameters1,obj2).limit(500);
and I am not getting anything.
The syntax of the Mongo Shell find function is:
db.collection.find(query, projection)
query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
projection document Optional. Specifies the fields to return in the documents that match the query filter.
When translating this for execution by the Mongo Java driver you need to construct separate BasicDBObject instances for;
the query
the projection
Here's an example:
MongoCollection<Document> table = ...;
// {"shapes.color": "red"}
BasicDBObject query = new BasicDBObject("shapes.color", "red");
// {_id: 0, 'shapes.$': 1}
BasicDBObject projection = new BasicDBObject("shapes.$", "1").append("_id", 0);
FindIterable<Document> documents = table
// assign the query
.find(query)
// assign the projection
.projection(projection);
System.out.println(documents.first().toJson());
Given the sample documents included in your question the above code will print out:
{
"shapes": [
{
"shape": "circle",
"color": "red"
}
]
}
This is identical to the output from db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});.
I'm trying to query mongodb with java. The name of my collection is: reads. Here is an example of a specific document I'm querying for:
{
"_id" : {
"d" : "B66929932",
"r" : "15500304",
"eT" : ISODate("2014-09-29T12:03:00Z")
},
"v" : 169000,
"iT" : ISODate("2015-04-10T20:42:07.577Z")
}
I'm trying to query where r = 15500304, eT = 2014-09-29T12:03:00Z and v = 169000. I'm able to do this in mongo pretty easily:
db.reads.find({ "_id.r" : "15500304", "_id.eT" : ISODate("2014-09-29T12:03:00Z"), "$where" : "this.v == 169000;"}).pretty()
I'm unable to figure out how to structure this in java. So far I've got:
DBCollection collection = db.getCollection("reads");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("_id.r", "15500304"));
obj.add(new BasicDBObject("_id.eT", "2014-09-29T12:03:00Z"));
obj.add(new BasicDBObject("v", 169000));
andQuery.put("$and", obj);
DBCursor cursor = collection.find(andQuery);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
My Question is: How do I query using these child nodes and return the matching document?
I'm unable to find any clear advice/examples online. Any and all advice is very appreciated.
You were close. Modify your query to:
DBCollection collection = db.getCollection("reads");
BasicDBObject query = new BasicDBObject();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateInString = "2014-09-29T12:03:00Z";
Date date = df.parse(dateInString);
query.append("status.name", "Expired")
.append("_id.eT", date)
.append("v", 169000);
Or using QueryBuilder:
DBObject query = QueryBuilder.start()
.put("_id.r").is("15500304")
.put("_id.eT").is(date)
.put("v").is(169000)
.get();
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
I have the following mongodb document
{
"user_100":{
"name": "Scott" ,
"uniqueDetails":{
"mobile":"9999999999",
"email": "scott#abc.com",
}
},
"user_101":{
"name": "Smith",
"uniqueDetails":{
"mobile":"9999999998",
"email": "smith#abc.com"
}
}
}
Now, when a new user signs up, I would like to check if a given mobile number/email already exists. Is there any solution for this with Java MongoDB API.
You can do a query and search in the collection for the tags that you want:
For example:
BasicDBObject query = new BasicDBObject("email", email_to_seach);
DBCursor cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
Also, you can look for only the first document that has the email or mobile phone that you want, with:
BasicDBObject query = new BasicDBObject("email", email_to_seach);
DBObject myDoc = coll.findOne(query);
You can use the com.mongodb.QueryBuilder class to build a query:
DBObject query = QueryBuilder.start("mobile").is(mobileNumberToSearch)
.or(QueryBuilder.start("email").is(emailToSearch).get()).get();
DBCursor dbCursor = collection.find(query);
if(dbCursor.hasNext()){
System.out.println("mobile number or email already exists");
}
I am having following mongo query which is executed in mongo shell.
db.test.update({
uuid: "160597270101684",
sessionId: "160597270101684.1"
}, {
$setOnInsert: {
stamps: {
currentVisit: "1377500985",
lastVisit: "1377500985"
}
},
$push:{
visits: {
page: "google.com",
method: "GET"
}
}
}, { upsert:true })
Because i am new to java, I am little bit confused to create the basicDBObject.
I had tried like this for sample
BasicDBObject doc = new BasicDBObject("uuid",1).append("session",2);
BasicDBObject upsertion = new BasicDBObject("upsert",true);
collection.update(doc,upsertion);
But its not working.
Any help will be great.
The upsert option isn't specified with a DBObject but with a third argument to DBCollection.update
public WriteResult update(DBObject q, DBObject o, boolean upsert, boolean multi)
You'll need to form a DBObject for update by appending $setOnInsert, $push, stamps and visits.
BasicDBObject update = new BasicDBObject();
BasicDBObject stamps = new BasicDBObject();
stamps.append("currentVisit", "1377500985").append("lastVisit", "1377500985");
BasicDBObject visits = new BasicDBObject();
update.append("$setOnInsert", stamps).append("$push", visits);
collection.update(doc, update, true);
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);