user2074252
user2074252

Reputation: 9

How to restrict the field in Mongodb

I have to restrict some field which are there in processtemplate class. Below is the method which i have developed. When i pass some id it gives me runtime exception. Please help me out

    public ProcessTemplate get(String id) throws GRIDRecordsDataManagerException {
    ProcessTemplate entity = null;
    try {

        BasicDBObject qry = new BasicDBObject();
        Map<String, Object> whereMap = new HashMap<String, Object>();
        whereMap.put("id", id);
        qry.putAll(whereMap);
        BasicDBObject field = new BasicDBObject();
        field.put("name", 1);
        field.put("status", 1);
        field.put("description", 1);

        DBCursor results = dbCollection.find(qry, field);

        if (results != null && results.hasNext()) {
            DBObject dbObj = results.next();
            entity = new ProcessTemplate();
            entity.setId((String) dbObj.get("id"));
            entity.setProcessName((String) dbObj.get("name"));
            entity.setStatus((String) dbObj.get("status"));
            entity.setDescription((String) dbObj.get("description"));

            System.out.println(entity);

        }
    } catch (Exception e) {

    }
    return entity;
}

Upvotes: 0

Views: 363

Answers (1)

Enrique Fueyo
Enrique Fueyo

Reputation: 3488

Answer copied from jira.mongodb.org

When querying a GridFS collection on specific fields, it works when no GridFS file was ever stored on that collection. Once a file was saved to the collection, the query on specific fields fails with "can't load partial GridFSFile file".

...

For now I'll reset the object associated with the collection, quite a hack though: if (Objects.equal(GridFSDBFile.class, coll.getObjectClass())) { coll.setObjectClass(null); }

...

Hi, A collection can have an associated ObjectClass and this information is cached, allowing it to be set once and then reused elsewhere in your code. Once it is set you have to explicitly unset it. GridFS is a specification for storing and retrieving files that is built upon the driver. GridFS is opinionated about how it is to be used, as such it sets the ObjectClass for the files collection when you create a GridFS instance. The reason it throws an error is the GridFSFile is not expected to be used in the way you've show as it could represent a partial part of a file and which is why it throws the "can't load partial GridFSFile file" runtime error. As you've found out the associated ObjectClass can only unset by resetting the ObjectClass back to null.

In your case it is translated to:

BasicDBObject qry = new BasicDBObject("id",id); //You can save 3 lines of code here, btw
BasicDBObject field = new BasicDBObject();
...
if (Objects.equal(GridFSDBFile.class, dbCollection.getObjectClass()))
 dbCollection.setObjectClass(null); 
DBCursor results = dbCollection.find(qry, field);
...

Upvotes: 1

Related Questions