Search code examples
c#mongodbmongodb-.net-drivermongodb-query

Filtering set of images from MongoDB


I have written some codes to store image files in MongoDB. Now I want to filter and retrieve some images from the mongoDB. I want to filter out some images which has some set of characters on the image name. For Ex: say I have stored aaaa_DEX.jpg, bbbb_DEX.jpg, cccc_BVX.jpg, dddd_OUI.jpg, eeee_DEX.jpg images in mongoDB and I want to get all the images which has the "DEX" on there names. Will it be possible with Query builder? How can I do this?

To upload I use:

public JsonResult UploadPrimaryImage(string hotelCode)
{
    var db = _hoteldbObj.Instance();
    var primaryImageBucket = new MongoGridFS(db, new MongoGridFSSettings() {Root = "HotelPrimaryImage"});

    foreach (string httpFile in Request.Files)
    {
        var postedFile = Request.Files[httpFile];

        if(postedFile == null)
            throw new InvalidOperationException("Invalid file");

        var bytes = ReadToEnd(postedFile.InputStream);

        using (var c = primaryImageBucket.Create(hotelCode, new MongoGridFSCreateOptions() { ContentType = postedFile.ContentType }))
        {                    
            c.Write(bytes, 0, bytes.Length);
            c.Flush();
            c.Close();
        }
    }

    return new JsonResult();
}

Thank You


Solution

  • Performing a .find("ABC") where ABC is your filename will handle this if querying on the full file name.

    If you want to query on a substring within the file name, my suggestion would be to save the substring as part of the metadata object. See this post for an example of working with metadata.