I am trying to filter my data based on the two factors. The first factor is the docID(object Id) and the second factor is DocType which is stored as metadata. The sample code I am pasting.I am also attaching the sample DB how it looks
like.
public async Task<ActionResult> DeleteDocument([FromRoute] int docType, [FromRoute] string docId)
{
try
{
var filter = Builders<GridFSFileInfo>.Filter.And(
Builders<GridFSFileInfo>.Filter.Eq(x => x.Metadata.GetValue("DocType"), docType),
Builders<GridFSFileInfo>.Filter.Eq(x => x.Id.ToString(), docId));
using (var cursor = await Bucket.FindAsync(filter))
{
var fileInfos = (await cursor.ToListAsync());
foreach (GridFSFileInfo fileInfo in fileInfos)
{
foreach (BsonElement bsonE in fileInfo.Metadata.ToList())
{
Console.WriteLine(fileInfo.Filename);
}
}
}
}
But I am not getting the correct result it giving me errors. Can anyone please point out what I am doing wrong or how to write filters based on metadata information.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Looks like they’re a few problems with the above code. The MongoDB Driver is struggling with converting these expressions into a MongoDB Query.
.Eq(x => x.Metadata.GetValue("DocType"), docType)
.Eq(x => x.Id.ToString(), docId)
This is because you need to use the indexer to accessing fields of the metadata, also you’ll need to change docId into the correct type before comparing it against the Id field.
Try the following filter out.
var docType = 1;
var docId = ObjectId.Parse("5f3ce002796ba13443aa4bc5");
var filter =
Builders<GridFSFileInfo<ObjectId>>.Filter.Eq(x => x.Metadata["DocType"], docType)
& Builders<GridFSFileInfo<ObjectId>>.Filter.Eq(x => x.Id, docId);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0