简体   繁体   中英

Execute complex mongo JSON query using C# mongo driver

I have following mongo shell query:

{'field':'FieldOne','value':'FieldOne','category':'categoryOne'} , { 'Color' : { '$elemMatch' : { 'Value' : 'Green' } }}

Is there any way to execute same query using C# mongo driver ?. I have tried using below C# code, but only the first one is getting executed:

 BsonDocument query = BsonDocument.Parse("{'field':'Overall','value':'Overall','category':'LoggedIncidents'} , { 'Priority' : { '$elemMatch' : { 'Value' : 'P1' } }}");
 QueryDocument queryDoc = new QueryDocument(query);
 var result = collection.Find(queryDoc).ToListAsync().Result;

The first item ( {'field':'FieldOne','value':'FieldOne','category':'categoryOne'} ) is being executed but not the second one ( { 'Color' : { '$elemMatch' : { 'Value' : 'Green' } }} ).

You are using it in find command if i'm not wrong. the first "{}" is what the filter condition for find is. next set of parameters are essentially to show/hide the fields you need. so if you want to filter by value of array "green" you can do this.

 db.objects.find({"color":{$elemMatch:{value:"green"}}})

should give you the results you are looking for. but if you want to specifically show/hide fields, you can do

 db.objects.find({"color":{$elemMatch:{value:"green"}}},{"field":1})

is this what you want to attain?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM