Java實現對mongoDB的兩表關聯查詢


Java實現對mongoDB的兩表關聯查詢

記錄一次學習java實現mongodb的兩表關聯查詢的過程,方便日后需要用到的時候進行回顧。

場景:mongodb中有兩張表,需要根據id進行關聯查詢。

表1數據如下:

表二數據如下:

實現兩張表的關聯查詢,需要用到mongodb的lookup,在查詢結果返回的時候,需要將沒有結果集為空的數據過濾掉,此時要用到mongodb的match。

java實現需要用到mongo-java-driver包,這里使用mongo-java-driver-3.9.0.jar。阿里的maven鏡像依賴如下

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.9.0</version>
</dependency>

Java代碼實現如下:

MongoClient mongoClient = new MongoClient("localhost", 27017);

//“test”為連接的數據庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

//test1是表1
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("test1");

List<Bson> aggregateList = new ArrayList<>(1);

//利用lookup進行關聯查詢
//test2是表2,兩個表根據id進行關聯,關聯的結果定義一個新的字段

/**Aggregates.lookup函數的說明:
     * lookup(final String from, final String localField, final String foreignField, final String as)
     * Creates a $lookup pipeline stage, joining the current collection with the one specified in from
     * using equality match between the local field and the foreign field
     * @param from         the name of the collection in the same database to perform the join with.
     * @param localField   the field from the local collection to match values against.
     * @param foreignField the field in the from collection to match values against.
     * @param as           the name of the new array field to add to the input documents.
     */
aggregateList.add(Aggregates.lookup("test2", "id", "id", "result"));

//利用match將沒有關聯到的結果過濾掉
aggregateList.add(Aggregates.match(Filters.ne("result", new ArrayList<String>(0))));
AggregateIterable<Document> aggregateIterable = mongoCollection.aggregate(aggregateList);
for (Document document : aggregateIterable) {
    System.out.println(document.toJson());
}

返回結果如下:

{ "_id" : { "oid" : "5e92c58671f9147a73e03662" }, "id" : "aaa", "keys" : ["name", "mobile"], "values" : ["姓名", "手機"], "result" : [{ "_id" : { "oid" : "5e92c48571f9147a73e0365f" }, "id" : "aaa", "name" : "張三", "mobile" : "12345678987" }, { "_id" : { "oid" : "5e92d5e871f9147a73e03667" }, "id" : "aaa", "name" : "李四", "mobile" : "12345678987" }] }

{ "_id" : { "oid" : "5e92c64e71f9147a73e03664" }, "id" : "ccc", "keys" : ["imsi", "mobile"], "values" : ["IMSI", "手機"], "result" : [{ "_id" : { "oid" : "5e92c73f71f9147a73e03665" }, "id" : "ccc", "imsi" : "28834765932", "mobile" : "12345678987" }] }

整個實現過程需要對mongodb中“管道”的概念有一定的理解。比如在這個場景中,首先通過lookup將關聯上的結果查詢出來,再通過“管道”將結果集交給match進行過濾。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM