問題描述
如何使用 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 Sangeetha、Rajat Goel、uma mahesh)
參考文件