【问题标题】:MongoDB Spring data Criteria.allMongoDB Spring 数据 Criteria.all
【发布时间】:2013-04-02 17:08:00
【问题描述】:

在 mongo 控制台中我有:

> db.test.find({})
{ "_id" : ObjectId("515afcfedba6a529520becfa"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 } ] }
{ "_id" : ObjectId("515b0e48dba6a529520becfd"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 }, {"key" :"three", "value" : 3 } ] }


> db.test.find({array: {$all:[{key:'one', value:1}, {key:'two',value:2}]}});
{ "_id" : ObjectId("515afcfedba6a529520becfa"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 } ] }
{ "_id" : ObjectId("515b0e48dba6a529520becfd"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 }, {"key" :"three", "value" : 3 } ] }

> db.test.find({_id:ObjectId("515afcfedba6a529520becfa"), array: {$all:[{key:'one', value:1}, {key:'two',value:2}]}});
{ "_id" : ObjectId("515afcfedba6a529520becfa"), "array" : [ { "key" : "one", "value" : 1 }, { "key" : "two", "value" : 2 } ] }

如何编写第二个和第三个查询: org.springframework.data.mongodb.core.query.Criteria ?

【问题讨论】:

    标签: java spring mongodb


    【解决方案1】:

    这是迄今为止我找到的最佳解决方案:

    ...
    
    DBObject obj = new BasicDBObject();
    obj.put( "key", 1 );
    obj.put( "value", "one" );
    DBObject obje1 = new BasicDBObject();
    obje1.put( "$elemMatch", obj );
    
    obj = new BasicDBObject();
    obj.put( "key", 2 );
    obj.put( "value", "two" );
    DBObject obje2 = new BasicDBObject();
    obje2.put( "$elemMatch", obj );
    
    Query qry = new Query( where("array").all(obje1, obje2) );
    
    ...
    

    【讨论】:

      【解决方案2】:

      这是一个我认为可行的选项:

      Criteria criteria = new Criteria("array");
      criteria.all(Criteria.where("key").is(1).and("value").is("one"),Criteria.where("key").is(2).and("value").is("two"));
      Query query = new Query(criteria);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-22
        • 2017-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        • 2016-09-03
        相关资源
        最近更新 更多