I have the following java-program, that should insert 2 records in the table testcoll:
package mongodbTest;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
public class HelloMongoDB {
public static void main(String[] args) {
Mongo mongo = null;
DB db=null;
DBCollection table=null;
// Connection to the MongoDB-Server
try {
mongo = new Mongo("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
//insert data
db = mongo.getDB("testdb");
table = db.getCollection("testcoll");
//create document and insert
BasicDBObject document = new BasicDBObject();
document.put("name", "Andre");
document.put("age", 34);
BasicDBObject document2 = new BasicDBObject();
document2.put("name", "Beatrix");
document2.put("age", 19);
table.insert(document);
table.insert(document2);
}
}
Like you can see, it should insert 2 records into the collection testcoll, but it only insert the first one.
> db.testcoll.find()
{ "_id" : ObjectId("54369b986d4b35dd1125e7ea"), "name" : "Andre", "age" : 34 }
Any suggestions?
Greetings, Andre
There is no problem with your code. You can add List of objects like this!!!
Try replacing "new Mongo" with "new MongoClient", which will default to acknowledged writes and therefore throw exceptions if any of the inserts fail.
See the Javadoc for the two classes, which explains the difference.
http://api.mongodb.org/java/current/com/mongodb/Mongo.html
http://api.mongodb.org/java/currrent/com/mongodb/MongoClient.html
You can also insert a list of documents using the overloaded insert method:
http://api.mongodb.org/java/current/com/mongodb/DBCollection.html#insert(java.util.List)
Related
I have read countless of articles and code examples on MongoDB Change Streams, but I still can't manage to set it up properly. I'm trying to listen to a specific collection in my MongoDB and whenever a document is inserted, updated or deleted, I want to do something.
This is what I've tried:
#Data
#Document(collection = "teams")
public class Teams{
private #MongoId(FieldType.OBJECT_ID)
ObjectId id;
private Integer teamId;
private String name;
private String description;
}
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.changestream.FullDocument;
import com.mongodb.client.ChangeStreamIterable;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.Arrays;
import java.util.List;
public class MongoDBChangeStream {
// connect to the local database server
MongoClient mongoClient = MongoClients.create("db uri goes here");
// Select the MongoDB database
MongoDatabase database = mongoClient.getDatabase("MyDatabase");
// Select the collection to query
MongoCollection<Document> collection = database.getCollection("teams");
// Create pipeline for operationType filter
List<Bson> pipeline = Arrays.asList(
Aggregates.match(
Filters.in("operationType",
Arrays.asList("insert", "update", "delete"))));
// Create the Change Stream
ChangeStreamIterable<Document> changeStream = collection.watch(pipeline)
.fullDocument(FullDocument.UPDATE_LOOKUP);
// Iterate over the Change Stream
for (Document changeEvent : changeStream) {
// Process the change event here
}
}
So this is what I have so far and everything is good until the for-loop which gives three errors:
There is a red line under 'for (', which says unexpected token.
There is a red line under ' :', which says ';' expected.
There is a red line under 'changeStream)', which says unknown class: 'changeStream'.
First of all you should put your code inside class method, not class body. Second - ChangeStreamIterable<Document> iterator element is ChangeStreamDocument<Document> and not Document.
Summing things up:
public class MongoDBChangeStream {
public void someMethod() {
// connect to the local database server
MongoClient mongoClient = MongoClients.create("db uri goes here");
// Select the MongoDB database
MongoDatabase database = mongoClient.getDatabase("MyDatabase");
// Select the collection to query
MongoCollection<Document> collection = database.getCollection("teams");
// Create pipeline for operationType filter
List<Bson> pipeline = Arrays.asList(
Aggregates.match(
Filters.in(
"operationType",
Arrays.asList("insert", "update", "delete")
)));
// Create the Change Stream
ChangeStreamIterable<Document> changeStream = collection.watch(pipeline)
.fullDocument(FullDocument.UPDATE_LOOKUP);
// Iterate over the Change Stream
for (ChangeStreamDocument<Document> changeEvent : changeStream) {
// Process the change event here
}
}
}
I'm storing a data from android studio into mongodb,storing the data is successful but retrieving is somewhat hard.
even though I find a way to read the data in mongodb it gives json objects in the server side.
I need a way to display that json objects into the textview of an android.
package com.example.prabhakaran.toiletfeedbacksystem;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
public class readDB {
public static void main(String[] args) {
comments(args);
feedback(args);
neo_checklist(args);
robin_checklist(args);
}
public static void comments(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database
.getCollection("testcollection");
List<Document> documents = collection.find().into(
new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
public static void feedback(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database
.getCollection("Comments");
List<Document> documents = collection.find().into(
new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
public static void neo_checklist(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database.getCollection("neo");
List<Document> documents = collection.find().into(new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
public static void robin_checklist(String[] args) {
MongoClient client = new MongoClient("172.20.9.122", 28018);
MongoDatabase database = client.getDatabase("raji");
MongoCollection<Document> collection = database
.getCollection("robin");
List<Document> documents = collection.find().into(
new ArrayList<Document>());
for(Document document : documents){
System.out.println(document);
}
}
}
Output
Document{ {_id=5c5020c08d5509385e1ac8f4, Value=robin, done=clean
toilet_bowl, Created_Date=Tue Jan 29 15:15:36 IST 2019} }
I have this type of data in the run window on android studio,but I want to have those data in the android app in textview or something.
so assist me in this issue,Thanks in advance.
I've saved Set<String> into mongodb as array and after that I want to load it again into Set<String>. How to do this?
My try returns exception:
package Database;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import java.util.HashSet;
import java.util.Set;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class StackOverflow {
public static void main(String[] args) {
// insert something to mongo:
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Set<String> namesOfTroysKids = new HashSet<>();
namesOfTroysKids.add("Paul");
namesOfTroysKids.add("Jane");
namesOfTroysKids.add("Mark");
namesOfTroysKids.add("Ivona");
Document doc = new Document("name", "Troy").append("height", 185).append("kids", namesOfTroysKids);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(eq("name", "Troy")).projection(fields(include("kids")));
Document d = findIt.first();
Set<String> kids = (Set<String>) d; // ERROR !!!
///Exception in thread "main" java.lang.ClassCastException: org.bson.Document cannot be cast to java.util.Set
//at Database.StackOverflow.main(StackOverflow.java:45)
}
}
There was method toArray() but it is for DBObject which is depreciated.
The document returned by your query is:
{
"_id": {
"$oid": "_id_value_"
},
"kids": [
"Mark",
"Ivona",
"Paul",
"Jane"
]
}
That obviously can not be implicitly coerced into a set. Its now just a matter of obtaining the kids from the document as a list and instantiating a Set from it:
public static void main(String [] args) throws Exception {
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Set<String> namesOfTroysKids = new HashSet<>();
namesOfTroysKids.add("Paul");
namesOfTroysKids.add("Jane");
namesOfTroysKids.add("Mark");
namesOfTroysKids.add("Ivona");
Document doc = new Document("name", "Troy").append("height", 185).append("kids", namesOfTroysKids);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(Filters.eq("name", "Troy")).projection(Projections.include("kids"));
Document d = findIt.first();
System.out.println("doc: " + d.toJson());
List<String> kidsList = (List<String>) d.get("kids", List.class);
Set<String> kidsSet = new HashSet<>(kidsList);
System.out.println("kids: " + kidsSet);
}
Basically an Iterable type is something that is meant to loop through. If you open a cursor using the Iterable type the only way to assign it to a java data type is to grab one iteration. You have done this by using the first method which will grab the first document returned by your query, note that if that is your intention you can use sort to control which Document is returned.
Below is the code. When i do this i generally do whatever i need to with the data one by one unless i need the entire dataset before i start my processing.
Set<String> kids = new Set<String>;
for(Document kidDoc : collection.find(eq("name", "Troy"))){
kids.add(kidDoc.getString("kids")))
}
I've found in mongodb tutorial for java about how to query from mongo collection but the eq which they use doesn't work for me! Do you know how to filter documents from a collection with mongo and java?
This is my try:
package Database;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class StackOverflow {
public static void main(String[] args) {
// insert something to mongo:
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Document doc = new Document("name", "Troy").append("height", 185);
collection.insertOne(doc);
doc = new Document("name", "Ann").append("height", 175);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(eq("name", "Troy"));
// ERROR!!! the method eq(String, String) is undefined!
mongo.close();
}
}
I want something like:
SELECT * from eqDoesntExcist WHERE name = "Troy"
You can use an eq Filter there as:
Bson bsonFilter = Filters.eq("name", "Troy");
FindIterable<Document> findIt = collection.find(bsonFilter);
or else to make it look the way doc suggests include a static import for the method call Filters.eq
import static com.mongodb.client.model.Filters.eq;
and further use the same piece of code as yours :
FindIterable<Document> findIt = collection.find(eq("name", "Troy")); // static import is the key to such syntax
you can not do this:
collection.find(eq("name", "Troy"));
because the compiler will expect in your class StackOverflow a method with the name eq and this is not what you need..
what you are looking for is defined in the Filter class
public static <TItem> Bson eq(String fieldName, Item value)
so it may be
collection.find(Filters.eq("name", "Troy"));
I am using the recent Solr 4.2.1 solrj libraries.
I am trying to execute an MLT Query from a java program. It works fine as long as I only provide small chunks in the stream.body, but that kind of defeats my purpose.
When I try to use the ContentStream I don't get a response back, when I do the solr.query, it makes another request.
It looks like the server is getting my solr.request() ok. Appreciate any pointers.
Oh, and I am talking to a solr 3.6.1
Here is what I have so far:
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.util.ClientUtils;
public class SolrJSearcher {
public static void main(String[] args) throws MalformedURLException, SolrServerException {
HttpSolrServer solr = new HttpSolrServer("http://localhost:8983/solr");
ModifiableSolrParams params = new ModifiableSolrParams();
String mltv[] = {"Big bunch of text for testing - redacted for brevity"};
String dvalues[] = {"mlt"};
String svalues[] = {"0"};
ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/mlt");
ContentStream cs = new ContentStreamBase.StringStream(mltv[0]);
up.addContentStream( cs);
SolrQuery theQuery = new SolrQuery();;
theQuery.set("qt", dvalues);
up.setParam("start", "0");
try {
solr.request(up);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
QueryResponse response = solr.query(theQuery);
SolrDocumentList results = response.getResults();
for (int i = 0; i < results.size(); ++i) {
System.out.println(results.get(i));
}
}
}
As far as I know, MoreLikeThis is meant to find documents similar to a document already in the index. If you're searching documents similar to an input string, then just insert a temporary item in your index before you do the query, and remove it afterwards.
I've been using the following successfully:
/*
* Build up a MoreLikeThis query to retrieve documents
* similar to the one with id originalId
*/
private SolrQuery buildUpMoreLikeThisQuery(String field3, String originalId) {
SolrQuery query = new SolrQuery();
query.setQueryType("/" + MoreLikeThisParams.MLT);
query.set(MoreLikeThisParams.MATCH_INCLUDE, true);
query.set(MoreLikeThisParams.MIN_DOC_FREQ, 1);
query.set(MoreLikeThisParams.MIN_TERM_FREQ, 1);
query.set(MoreLikeThisParams.MIN_WORD_LEN, 7);
query.set(MoreLikeThisParams.BOOST, false);
query.set(MoreLikeThisParams.MAX_QUERY_TERMS, 1000);
query.set(MoreLikeThisParams.SIMILARITY_FIELDS,
"field1,field2");
query.setQuery("id:" + originalId);
query.set("fl", "id,score");
query.addFilterQuery("field3:" + field3);
int maxResults = 20;
query.setRows(maxResults);
return query;
}