【问题标题】:How to execute native mongo shell query from java code?如何从 java 代码执行本机 mongo shell 查询?
【发布时间】:2020-08-22 15:47:42
【问题描述】:

有没有办法以与 mongo shell 中的相同格式执行 mongo 查询或 js 脚本?

示例查询:

db.getCollection('MyCollection').aggregate([
    {
        "$unwind": "$rootElement.list"
    },
    {
        "$match": {$expr: {$eq: ["$rootElement.list.elementId", "$rootElement.elementId"]}}
    }
]

我只想将此查询作为字符串或 query.js 文件获取并从 java 代码执行。

在 4.2 版本中,MongoDB 删除了 eval 命令,但是还有其他替代方法吗? 谢谢。

【问题讨论】:

    标签: java mongodb mongodb-query mongo-shell mongo-java-driver


    【解决方案1】:

    见以下代码

    BsonArray bsonValues = BsonArray.parse("script")
    
    LinkedList<BsonDocument> documents = bsonValues.stream().map(x -> x.asDocument()).collect(Collectors.toCollection(LinkedList::new))
    
    MongoCursor<Document> iterator = collection.aggregate(documents).iterator();
    
    if(iterator.hasNext()){
        return IteratorUtils.toList(iterator);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-24
      • 2013-04-25
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      相关资源
      最近更新 更多