Query on MongoDB GridFS metadata (Java)

你说的曾经没有我的故事 提交于 2019-11-30 12:46:56

Unfortunately I didn't get it to work with nested BasicDBObjects.

Finally I was using the dot notation which works fine:

// This query fetches the files I need
BasicDBObject query = new BasicDBObject("metadata.target_field", "abcdefg"));
List<GridFSDBFile> files = gridFs.find(query);

From MongoDB documentation (http://docs.mongodb.org/manual/tutorial/query-documents/#exact-match-on-the-embedded-document):

Exact Match on the Embedded Document

To specify an equality match on the whole embedded document, use the query document { : } where is the document to match. Equality matches on an embedded document require an exact match of the specified , including the field order.

Equality Match on Fields within an Embedded Document

Use the dot notation to match by specific fields in an embedded document. Equality matches for specific fields in an embedded document will select documents in the collection where the embedded document contains the specified fields with the specified values. The embedded document can contain additional fields.


I wrote a simple code to translate the "document notation" in "dotted notation" . I hope it's useful.

protected static void toDottedJson(Object o, String key, DBObject query) {
    if (o instanceof Map)
        for (Entry<?, ?> c : ((Map<?, ?>) o).entrySet())
            toDottedJson(c.getValue(), key + "." + c.getKey().toString(),
                    query);
    else
        query.put(key, o.toString());
}

public static DBObject buildMetadataSearchQuery(DBObject searchQuery) {
    BasicDBObject metadatSearchQuery = new BasicDBObject();
    for (Entry<?, ?> c : ((Map<?, ?>) searchQuery).entrySet())
        toDottedJson(c.getValue(), "metadata."
                + c.getKey().toString(),
                metadatSearchQuery);
    return metadatSearchQuery;
}

For your purpose:

List<GridFSDBFile> files = gridFs.find(buildMetadataSearchQuery(new BasicDBObject("target_field", "abcdefg")));
Tiago Pereira

Simpler:

GridFSDBFile gridFile = fsDocs.findOne(new BasicDBObject("md5","1b21bc40a456befc7d2ee10b0e25fabf"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!