Question

I am new to MongoDB so please excuse my ignorance.

I have a mongoDB which contains a bunch of documents with something like this

["field": "blah", "version":"1" ...]
["field": "blah", "version":"2" ...]
["field": "blah", "version":"1"....]
["field": "blah1", "version":"10"...]
["field": "blah2", "version":"100"...]
["field": "blah3", "version":"1"....]
["field": "blah3", "version":"2"....]
["field": "blah2", "version":"1"....

I am trying to send a list of queries and fetch all the records as a batch. Is it possible to do so?

List<Docs> fetchDocs(Map<String, String> queries)
{
     CriteriaContainer cc=null;
     Query<Docs> query = this.mongoDao.createQuery(MyClass.class);
     for (Map.Entry<String,String >entry : queries.entrySet())
     {
          if(cc ==null)
          {
            cc= query.criteria("Field").equal(entry.getKey()).and(query.criteria("version").equal(entry.getValue()));
          }
          else
          {
            cc.or(query.criteria("Field").equal(entry.getKey()).and(query.criteria("version").equal(entry.getValue()));)
          }

    }
    query.and(cc);
    List<Docs> doc = query.asList();

    return doc;
}

I am not geting the correct list back. I am not sure if I have written this query correctly.

essentially, I want to fetch results or query like this

[{"Field":"blah,"version":1 } $or {"Field":"blah1", "version":10} ]

It should return me a list containing

["field": "blah", "version":"1" ....]

["field": "blah1", "version":"10"....]
Était-ce utile?

La solution 2

I ended up fixing my query to this which worked. Wanted to share it with the rest

List<Docs> fetchDocs(Map<String, String> queries){
        Criteria [] c = new Criteria[queries.size()];
        Query<TUCacheDoc> query0 = this.mongoDao.createQuery(MyClass.class);
        int counter=0;
        for (Map.Entry<String, String> entry : inMap.entrySet()) {
            Query<TUCacheDoc> queryC = this.mongoDao.createQuery(MyClass.class);
            String key= entry.getKey();
            String val= entry.getValue();
            Criteria cC = queryC.criteria("field").equal(key).criteria("version").equal(val);
            c[counter]=cC;
            counter++;
        }

        query0.or(c);
        List<TUCacheDoc> qresult = query0.asList();

return qresult;
}

Autres conseils

Yes, this is definitely possible to do. The final query object will look more like this, however:

{$or: [{"field": "blah,"version":1 }, {"field":"blah1", "version":10} ]}

Notice the array of subqueries for the $or expression.

There are some quirks in Morphia will mean you have to wrap it in an $and clause. So your code would be like this:

Query q = dao.createQuery();
q.and(
  q.or(subQuery1),
  q.or(subQuery2),
 ...
);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top