I want to search a string in multiple values of all the MongoDB documents and return matched documents in return.
This is what I have tried to do it with one key
BasicDBObject object = new BasicDBObject();
object.put("firstName", Pattern.compile(value));
FindIterable<Document> documents = mongoCollection.find(object)
.skip(size*(index - 1)).limit(size);
for (Document document : documents) {
customerList.add(CustomerMapper.map(document));
}
return customerList;
How can I change it to search a value in all key/values?
I have firstName, lastName, email, phoneNumber in every document of the customers collection.
Suggestions?
Fixed it by using following code:
BasicDBObject orQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("firstName", new BasicDBObject("$regex", value).append("$options", "i")));
obj.add(new BasicDBObject("lastName", new BasicDBObject("$regex", value).append("$options", "i")));
obj.add(new BasicDBObject("email", new BasicDBObject("$regex", value).append("$options", "i")));
obj.add(new BasicDBObject("phoneNumber", new BasicDBObject("$regex", value).append("$options", "i")));
orQuery.put("$or", obj);
FindIterable<Document> documents = mongoCollection.find(orQuery)
This helped me to use selected keys to use for searching.
Related
I try to find a document in my collection that contains document as well.
when i search only with primitive fields like the name and age it works but when i add the grades its doesn't find the document in my collection
List<Bson> bsonList = new arrayList<>();
bsonList.add(new Document("name", "john"));
bsonList,add(new Document("age", 19));
Map<String, Integer> = grades = new HashMap<>();
grades.put("math", 9);
grades.put("english", 10);
bsonList.add(new Document("grades", grades);
FindIterable<Document> result = applicationContext.getBean(MongoConnection.class)
.getCollection(myDb, myCollection)
.find(Filters.and(bsonList));
I want to get max timestamp of a set of tags from MongoDb history database. Say the tag ids are 1,2,3,4,5 I want to check all records for these tags and get the timestamp of latest. My collection looks like this along with data:
My code is as follows:
protected Timestamp getMaxRealTimeHistoryTimestamp(List<Integer> tagIds)
{
try
{
MongoClient mongo = new MongoClient(m_connectionInfo.getHost(), m_connectionInfo.getPort());
//Connecting to the database
MongoDatabase database = mongo.getDatabase(m_connectionInfo.getDatabaseName());
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<>();
obj.add(new BasicDBObject("TAG_ID", new BasicDBObject("$in", tagIds)));
MongoCollection<Document> collection = database.getCollection("EM_HISTORY");
Document doc = collection.find(andQuery).sort(new Document("TIME_STAMP", -1)).first();
if(doc != null)
{
return new Timestamp(((Date) doc.get("TIME_STAMP")).getTime());
}
}
catch (Exception e)
{
if (Logger.isErrorEnabled())
Logger.error(e);
}
return null;
}
the doc variable has some strange row that is not even in the collection
What am I doing wrong here?
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<>();
obj.add(new BasicDBObject("TAG_ID", new BasicDBObject("$in", tagIds)));
You are never adding the query filters from obj back into your andQuery, so the code ends up querying the collection without any filter.
I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. I want to update the value the document having its ID. In order to do that I tried to use the following two approaches (found in Stackoverflow and MongoDB Blog):
Approach #1:
for(String docID : expiredDocsIDs) {
Bson filter = Filters.eq("_id", docID);
Bson updates = Updates.set("isExpired", true);
dbCollection.findOneAndUpdate(filter, updates);
}
Approach #2:
expiredDocsIDs.stream()
.forEach(docID -> {
BasicDBObject searchQuery = new BasicDBObject("_id", docID);
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("isExpired", true);
updateFields.append("fetchStatus", "FETCHED");
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
dbCollection.updateOne(searchQuery, setQuery);
});
None of these approaches does not work.
It iterates over the list of documents IDs, executes the code but at the end of the code, when I check the documents in DB there is no any change in the documents' field I tried to update.
How can I update the specific document in MongoDB?
As BlakesSeven correctly noted, the problem was with a casting of _id field. The original code sent this parameter as String while the correct way is to send a parameter of ObjectId type.
The correct and worked code form MongoDB 3.2:
this.trackedEpisodesReg.entrySet().stream()
.filter(ep -> ep.getValue().isExpired())
.forEach(ep -> {
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("isExpired", true);
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
BasicDBObject searchQuery = new BasicDBObject("_id", new ObjectId(ep.getValue().getEpisodeID()));
dbCollection.updateOne(searchQuery, setQuery);
});
I am using mongo db driver 2.11.2. I am bit puzzled how to insert/add an array to the BasicDBObject. All the example which I come across are does not show how to achieve this :(. In the below example how would I insert employees array in the dbo object ?
/*
{
"company" : "stackoverflow",
"established": "when I started coding"
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
*/
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("company", "stackoverflow");
basicDBObject.put("established", "when I started coding");
System.out.println(basicDBObject.toString());
}
Use the Arrays.asList as a contructor for the list. It's just a list. And .append() the object keys rather than "put". Again, it's just as HashMap interface:
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("company", "stackoverflow");
basicDBObject.append("established", "when I started coding");
basicDBObject.append("employees", Arrays.<DBObject>asList(
new BasicDBObject("firstName", "john")
.append("lastName", "doe"),
new BasicDBObject("firstName", "anna")
.append("lastName", "smith"),
new BasicDBObject("firstName", "peter")
.append("lastName", "jones")
));
System.out.println(basicDBObject.toString());
I am using a Java driver to run some mongo text searches.
An example of my previous code is (where values is a String passed in):
DBCollection coll = db.getCollection("testCollection");
//create the basic object
DBObject searchCmd = new BasicDBObject();
//create the search cmd
searchCmd.put("text", "testCollection"); // the name of the collection (string)
// define the search word
searchCmd.put("search", value); // the term to search for (string)
// define the return values
searchCmd.put("project", new BasicDBObject("score", 1).append("name", 1).append("path", 0).append("_id", 0));
// get the results
BasicDBObject commandResult = db.command(searchCmd);
// Just out the results key
BasicDBList results = (BasicDBList) commandResult.get("results");
then I loop over the "results" and I get for each it score by
// Get the number ii
BasicDBObject element = (BasicDBObject) results.get(ii);
// Now get the score
double score = (double) element.get("score");
I want to upgrade to use find since that seems the way 2.6 and later prefers it. So far I have:
DBCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject();
query.append("$text", new BasicDBObject("$search", value));
DBCursor cursor = coll.find(query);
However, I am not sure how to get the score.
I tried doing something like:
query.append("score", new BasicDBObject("$meta", "textScore"));
But this does not work. I would like to be able to get the name and the score so that I can then insert them into a new collection that will also hold the score.
I can get the name easily by:
while (cursor.hasNext())
{
DBObject next = cursor.next();
String name = next.get("name").toString();
}
But how do I get the score?
I found this interesting page: http://api.mongodb.org/java/current/
it appears that find can take a second DBObject which has the fields.
I created a new object:
BasicDBObject fields = new BasicDBObject();
fields.append("score", new BasicDBObject("$meta", "textScore"));
and I am calling find using:
DBCursor cursor = coll.find(query, fields);
and now I can get the score the same way I can get the name.