简体   繁体   中英

Running custom mongodb queries in java

I want to run raw mongoDb queries using runCommand() which takes in BSON data. Following is my code

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("MyDB");
    MongoCollection<Document> collection = (MongoCollection<Document>)database.runCommand(??);        

If my query is

db.mycol.find({"by":"tutorials point"}).

What should be BSON data that I have to pass inside runCommand()? Is it only

{{"by":"tutorials point"}}

or

db.mycol.find({"by":"tutorials point"}).

And If instead of find() i have to use Insert() how to go about it??

Find:

db.runCommand({
    find: "mycol",
    filter: { by: "tutorials point"}
})

Insert:

db.runCommand({
    insert: "mycol",
    documents: [ { _id: 1, foo: "bar"} ]
})

I think the easiest why to do it in java is to use Jongo ( http://jongo.org/ ). Syntax is very similar to mongo shell.

jongo.runCommand("{find: 'mycol', filter: { by: 'tutorials point'}}")

You can not do that. First of all you need to get your collection

like : MongoCollection<Document> collection = database.getCollection("test");

Once you have the collection you can run the raw query by using the util import com.mongodb.util.JSON;

this would be an example that you want to do:

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("MyDB");
MongoCollection<Document> collection = database.getCollection("mycol");

String rawQuery = "{\"by\": \"tutorials point\"}";

DBObject query = (DBObject) JSON.parse(rawQuery);
collection.find(query);

Give example of how it work this was my query

db.getCollection('Collection').aggregate([{
    $unwind: '$somearray'
}, {
    $match: {
        _id: ObjectId("123456"),
        'somearray.type': "blabla"
    }
}, {
    $project: {
        '_id':0,
        'name': '$somearray.name',
        'phone': '$phone'
    }
}])

This was my Java program that did the same as query

public MongoIterable < Document > GetList(String collectionName, String id) {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("MyDB");
    MongoCollection < Document > collection = database.getCollection("collectionName");
    Document match = Document.parse("{_id: ObjectId('" + id + "'),'somearray.type': 'blabla'}");
    Document project = Document.parse("{ $project: { _id: 0,'name': '$somearray.name'},  'phone': '$phone'}");
    MongoIterable < Document > output = collection.aggregate(Arrays.asList(Aggregates.unwind("$somearray"), Aggregates.match(match), project));
    return output;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM