亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 java 中運行自定義 mongodb 查詢

在 java 中運行自定義 mongodb 查詢

海綿寶寶撒 2022-07-20 19:24:04
我想使用接收 BSON 數據的 runCommand() 運行原始 mongoDb 查詢。以下是我的代碼    MongoClient mongoClient = new MongoClient();     MongoDatabase database = mongoClient.getDatabase("MyDB");     MongoCollection<Document> collection = (MongoCollection<Document>)database.runCommand(??);如果我的查詢是db.mycol.find({"by":"教程點"})。我必須在 runCommand() 中傳遞的 BSON 數據應該是什么?難道只有{{"by":"教程點"}}或者db.mycol.find({"by":"教程點"})。如果不是 find() 我必須使用 Insert() 怎么辦?
查看完整描述

3 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

尋找:


db.runCommand({

    find: "mycol",

    filter: { by: "tutorials point"}

})

插入:


db.runCommand({

    insert: "mycol",

    documents: [ { _id: 1, foo: "bar"} ]

})

我認為在 java 中這樣做最簡單的原因是使用 Jongo ( http://jongo.org/ )。語法與 mongo shell 非常相似。


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


查看完整回答
反對 回復 2022-07-20
?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

舉例說明它是如何工作的這是我的查詢


db.getCollection('Collection').aggregate([{

    $unwind: '$somearray'

}, {

    $match: {

        _id: ObjectId("123456"),

        'somearray.type': "blabla"

    }

}, {

    $project: {

        '_id':0,

        'name': '$somearray.name',

        'phone': '$phone'

    }

}])

這是我的 Java 程序,它和查詢一樣


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;

}


查看完整回答
反對 回復 2022-07-20
?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

你不能這樣做。首先你需要得到你的collection


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


擁有后,collection您可以使用 util 運行原始查詢import com.mongodb.util.JSON;


這將是您想要做的一個例子:


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


查看完整回答
反對 回復 2022-07-20
  • 3 回答
  • 0 關注
  • 245 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號