在纯Javascript中,我可以写一个这样的查询:
db.getCollection('someTable').find({
someArray:{$elemMatch:{$eq:ObjectId("SomeObjectId")}}
});
现在我需要用Java编写这个。 像this.collection.find()。过滤器......
但我似乎没有把它弄好。上面的陈述如何翻译成java?
由于
答案 0 :(得分:0)
为此,您需要将mongo-client用于java程序。
以下是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为java下载最新的mongo驱动程序
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.0.0-rc0</version>
</dependency>
答案 1 :(得分:0)
这可能就是你要找的东西:
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"))))));