Build dynamic queries with Spring Data MongoDB Criteria

旧巷老猫 提交于 2019-12-06 06:03:30

问题


I would like to run a bulk delete operation on a list of documents in MongoDB that have been selected by the user in the UI so I need to dynamically build a query that looks like the following (the or clause expands for every document selected):

{
    $and: [
        {
            "contentType": "application/vnd.sometype"
        },
        {
            $or: [
                {
                    "metadata.name": "someName",
                    "metadata.version": "someVersion"
                },
                {
                    "metadata.name": "someOtherName",
                    "metadata.version": "someOtherVersion"
                }
            ]
        }
    ]
},
Fields: null,
Sort: null

Just now I'm using string concatenation to achieve this.

Is it possible to build this query with the Spring Data MongoDB Criteria Builder (org.springframework.data.mongodb.core.query.Criteria)?


回答1:


Doesn't this work for you?

Criteria criteria = Criteria.where("contentType").is("application/vnd.sometype");

List<Criteria> docCriterias = new ArrayList<Criteria>(docs.size());

for (Document doc: docs) {
    docCriterias.add(Criteria.where("metadata.name").is(doc.getName())
                               .and("metadata.version").is(doc.getVersion()));
}

criteria = criteria.orOperator(docCriterias.toArray(new Criteria[docs.size()]));

?



来源:https://stackoverflow.com/questions/24562481/build-dynamic-queries-with-spring-data-mongodb-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!