Query Collections containing an ObjectId within an Array in Mongo with Java - java

in pure Javascript, I can write a query like this:
db.getCollection('someTable').find({
someArray:{$elemMatch:{$eq:ObjectId("SomeObjectId")}}
});
Now I need to write this in Java.
Something like this.collection.find().filter...
But I don't seem to get it right. How's the statement above translated to java?
Thanks

This may be what you looking for:
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase("test");
db.getCollection("someTable").find(new BasicDBObject("someArray", new BasicDBObject("$elemMatch", new BasicDBObject("$eq", new BsonObjectId(new ObjectId("SomeObjectId"))))));

For this you need to use mongo-client for java program.
Here is some snippet from mongo java
import com.mongodb.ErrorCategory;
import com.mongodb.MongoWriteException;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;
import sun.misc.BASE64Encoder;
public class DocumentDAO {
final MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURIString));
final MongoDatabase mongoDatabase= mongoClient.getDatabase("Db");
public DocumentDAO(final MongoDatabase mongoDatabase) {
someCollection= mongoDatabase.getCollection("SomeCollecton");
}
Bson filter =new Document("objectId",objectName);
List <Document> all= someCollection.find(filter).into( new ArrayList<Document>());
for(Document cur:all)
{
obj=cur;
}}
Maven could be used to download latest mongo driver for java
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.0.0-rc0</version>
</dependency>

Related

How to specify a ReadConcern to use with Spring's MongoTemplate?

With the vanilla java MongoClient you can specify a read concern for a particular query for example like this:
var result = mongoClient.getDatabase("somedb")
.getCollection("collection")
.withReadConcern(ReadConcern.MAJORITY)
.find(..)
But I cannot seem to find a way to set the ReadConcern using Spring's MongoTemplate. Preferably I'd like to set it for a specific query, but if this is not possible I'm fine with configuring something equivalent to a WriteConcernResolver (but for read concerns).
Is this possible, and if so how?
I'm using spring-data-mongodb version 3.2.6.
It seems that you maybe able to set this on the TransactionOptions and MongoTransactionManager:
https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/MongoTransactionManager.html
Example:
TransactionOptions transactionOptions = TransactionOptions.builder().readConcern(ReadConcern.LOCAL).writeConcern(WriteConcern.W1).build();
return new MongoTransactionManager(dbFactory.getMongoDatabaseFactory(), transactionOptions);
=== Edited ===
How about we take it the MongoClient route, since you stated it works on it? We could create a MongoTemplate from a given MongoClient instance:
Example:
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.ReadConcern;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
#Configuration
public class DemoApplication extends AbstractMongoClientConfiguration {
#Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "someDbName");
}
#Override
public MongoClient mongoClient() {
final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/someDbName");
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.readConcern(ReadConcern.DEFAULT)
.writeConcern(WriteConcern.MAJORITY)
.readPreference(ReadPreference.primary()).build();
return MongoClients.create(mongoClientSettings);
}
#Override
protected String getDatabaseName() {
return "someDbName";
}
}

Cannot iterate through MongoDB Collection

As a step towards familiarising myself with MongoDB, I started to create simple Java Classes to perform CRUD in MongoDB. I was able to establish connection with MongoDB. Nevertheless, when I try to iterate through the MongoDB collection, I'm getting errors. Implemented Java class is shared here.
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.Iterator;
import org.bson.Document;
public class ReadMongo {
public static void main( String args[] ) {
//Creating a MongoDB client
com.mongodb.client.MongoClient mongo = MongoClients.create("mongodb://localhost:27017");
//Connecting to the database
MongoDatabase database = mongo.getDatabase("myDB");
//Creating a collection object
MongoCollection<Document> collection = database.getCollection("myGrid");
//Retrieving the documents
FindIterable<Document> iterDoc = collection.find();
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Below I've shared the error log.
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.internal.operation.SyncOperations.<init>(Lcom/mongodb/MongoNamespace;Ljava/lang/Class;Lcom/mongodb/ReadPreference;Lorg/bson/codecs/configuration/CodecRegistry;Lcom/mongodb/WriteConcern;Z)V
at com.mongodb.client.internal.MongoCollectionImpl.<init>(MongoCollectionImpl.java:106)
at com.mongodb.client.internal.MongoDatabaseImpl.getCollection(MongoDatabaseImpl.java:132)
at com.mongodb.client.internal.MongoDatabaseImpl.getCollection(MongoDatabaseImpl.java:127)
at ReadMongo.main(ReadMongo.java:14)
The line #14 corresponds to MongoCollection<Document> collection = database.getCollection("myGrid"); line.
I still don't know what's wrong with the above code. Nevertheless, I was able to solve this issue following these resources: (i) resource 1 and (ii) resource 2. The final working solutions is as follows.
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDB {
public static MongoClient mongoClient;
public static MongoDatabase database;
public static void main(String[] args) {
mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
database = mongoClient.getDatabase("myDB");
FindIterable<Document> mydatabaserecords = database.getCollection("myGrid").find();
MongoCursor<Document> iterator = mydatabaserecords.iterator();
while (iterator.hasNext()) {
Document doc = iterator.next();
System.out.println(iterator.next());
}
}
}

JMeter / Beanshell “Error invoking bsh method: eval Sourced file:”

I am trying to call a method from java to connect to the mongoDB database, my machine can do it successfully but if I run it with a different one, I get this error.
2020-07-15 12:57:21,751 ERROR o.a.j.u.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import test.MongoDB; MongoDB.connect(vars.get("uri"));'' : Method Invocation MongoDB.connect
What could be the problem?
java
import java.util.LinkedHashMap;
import java.util.Map;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDB {
public static MongoDatabase database;
public static MongoClient mongoClients;
public static void connect(String uri) {
MongoClientURI uri_1 = new MongoClientURI(uri);
// Connecting With Server
mongoClients = new MongoClient(uri_1);
System.out.println("server connection successfully done");
database = mongoClients.getDatabase("Capacitacion");
System.out.println("Connect to database successfully");
System.out.println("DataBase Name: " + database.getName());
MongoCollection<Document> col_Capacitacion_Liceo = database.getCollection("Liceo");
} ```
jmeter
```import test.MongoDB;
MongoDB.connect(vars.get("uri"));;```
*
Beanshell is not Java and it doesn't support Diamond Operators
If for some reason you really need to use Beanshell - change this line:
MongoCollection<Document> col_Capacitacion_Liceo = database.getCollection("Liceo");
to this one:
MongoCollection col_Capacitacion_Liceo = database.getCollection("Liceo");
But be aware that starting from JMeter 3.1 users are encouraged to use JSR223 Test Elements and Groovy language for scripting.
You may also find MongoDB Performance Testing with JMeter article useful

Why eq doesn't exist for mongo-java-driver?

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"));

Bson cannot be resolved with Mongo DB /Java

I am getting this error on the last line in code below:
The type org.bson.conversions.Bson cannot be resolved. It is indirectly referenced from required .class files, I am using Mongo JavaDriver 3.0.2
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;
public class InsertDriver {
public static void main(String[] args)
{
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("postsdb");
DBCollection collection = db.getCollection("posts");
BasicDBObject doc1 = new BasicDBObject();
doc1.put("user", "Mike");
doc1.put("sports", "soccer");
doc1.put("tweet", "Hi..");
//String json = JSON.serialize( doc1);
//BasicDBObject bson = (BasicDBObject) JSON.parse( json );
List<BasicDBObject> docs = new ArrayList<BasicDBObject>();
docs.add(doc1);
collection.insert(docs); //ERROR HERE
}
}
Had the same issue. I've solved it by downloading the bson jar and adding it to the search path.
The Mongodb documentation states the following:
You can also download the jars directly from sonatype. Note:
mongodb-driver requires the following dependencies: bson and
mongodb-driver-core

Categories

Resources