2

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 ??

3 Answers 3

1

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'}}")
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.