如何使用 java 代碼轉換 mongodb 查詢 (How to Transform mongodb query using java code)


問題描述

如何使用 java 代碼轉換 mongodb 查詢 (How to Transform mongodb query using java code)

我是 MongoDB 的新手。我想將此 mongo DB 查詢轉換為 java 代碼。我已經嘗試了一點。但我有一個問題。請,如果有人幫助意味著這對我來說將是一個很大的幫助。提前致謝。

db.getCollection('test').aggregate(
  [{
      $match: {
        "ids": 9999999,
        $or : [{"tags.name":"roja"},{"tags.location":"US"},{"tags.year":2019}]
      }
    },
    {
      '$facet': {
        metadata: [{ $count: "total" }],
        data: [{
          $addFields: {
            "weight": {
              $map: {
                input: "$tags",
                as: "tagsEl",
                in: {
                  "$add": 
                    [              
                      {$cond: [ { $eq: [ '$$tagsEl.roja', 'roja' ] }, 15, 1 ]} ,
                      {$cond: [ { $eq: [ '$$tagsEl.location', 'US' ] }, 10, 1 ]},
                      {$cond: [ { $eq: [ '$$tagsEl.year', 2019 ] }, 5, 1 ]}                    
                    ]
                }
              }
            }
          }
        }, { $skip: 0 }, { $limit: 10 }, { '$sort': { 'weight' : ‑1 } }]
      }
    }
  ]
)

參考解法

方法 1:

You can use Studio3T to directly convert your query into java code, unless you don't get comfortable with the syntax.

https://studio3t.com/knowledge‑base/articles/query‑code/

方法 2:

//Get database
MongoDatabase db = mongoClient.getDatabase("testdb");

//get collection
MongoCollection<Document> testCol = db.getCollection("test");

//prepare a list of aggregation pipeline stages.
List<Bson> aggs = new ArrayList<>();

//each pipeline stage you wrote is in js. the equivalent java syntax is...

//for {key1:value1,key2:value2}
new Document().append("key1","value1").append("key2","value2")

//for array such as ["abc",1,{key3,value3}]
Arrays.asList("abc",1,new Document("key3","value3"))

//for example , part of your script can be implemented in java as below.
aggs.add(
new Document("$match",//match aggregation pipeline stage
new Document("ids",9999999)
.append("$or",Arrays.asList(
new Document("tags.name","roja"),
new Document("tags.location","US"),
new Document("tags.year",2019)
))
)
);
//you can add as many stages as you need to aggs list.
//execute
MongoCursor<Document> cursor = testCol.aggregate(aggs).iterator();
while(cursor.hasNext()){
Document d = cursor.next();
//do your operation.
}
</code></pre>

(by SangeethaRajat Goeluma mahesh)

參考文件

  1. How to Transform mongodb query using java code (CC BY‑SA 2.5/3.0/4.0)

#mongodb-java #mongoDB






相關問題

GridFS Java 對像是線程安全的嗎? (Are GridFS Java objects thread safe?)

Драйвер MongoDB Java: такога cmd: aggregate няма (MongoDB Java driver : no such cmd: aggregate)

Стварэнне парадкавага нумара ў mongoDB (Generating sequence number in mongoDB)

MongoDB java驅動如何判斷副本集是否處於自動故障轉移過程中? (How can MongoDB java driver determine if replica set is in the process of automatic failover?)

優化 mongodb 中的查詢 (Optimising queries in mongodb)

查詢數據時應該使用 MongoTemplate 還是 DBCollection (Should i use MongoTemplate or DBCollection when query data)

org.bson.codecs.configuration.CodecConfigurationException:找不到類 [Ljava.lang.String; 的編解碼器; (org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;)

如何使用 Java MongoDB 驅動程序檢索字段子集? (How to retrieve a subset of fields using the Java MongoDB driver?)

當使用 karras 和 clojure 給出字段時,如何更新 MongoDB 中的文檔? (How to update a Document in MongoDB when a field is given with karras & clojure?)

如何使用 java 代碼轉換 mongodb 查詢 (How to Transform mongodb query using java code)

MongoDB 文檔使用 Java 中的 findOneAndUpdate 方法更新數組元素 (MongoDB document update array element using findOneAndUpdate method in Java)

aws documentdb 是否為兩種方式的 ssl 驗證 mongodb 客戶端證書? (Does aws documentdb validate mongodb client certificate for two way ssl?)







留言討論