-1

I need to execute the following MongoDB query using C# driver to execute a javascript function on a field of type "Code" and check data inside contains a guid asa a string:

The mongodb query that works is this:

db.getCollection('BackgroundTasks').find({ Status: 1, $where: function() {
        if (this.Settings.hasOwnProperty("ID")){
            return this.Settings.ID== "606d7afb-3dce-4533-8f8d-6411715e5b47";
        }        
        return false;
    }
}) 

Need the C# version of code using Builders filter from the new API.

Dio
  • 21
  • 1
  • 3
  • Hi Dio, and welcome to Stack Overflow! Can you show us what you've tried so far, and to what extent it has worked or not? Remember, you're encouraged to [edit] and re-edit your question to make it as clear and useful as possible. – Vince Bowdren Sep 08 '16 at 08:03

2 Answers2

1

Solution that worked for me:

var collection = _database.GetCollection<BsonDocument>("BackgroundTasks");
var jsFilter = new BsonDocument(new BsonDocument("$where", new BsonJavaScript("function() { if (this.Settings.hasOwnProperty('TranslationMemoryId')){return this.Settings.TranslationMemoryId == '"+tmid.ToString()+"';}return false; }")));
var filter = jsFilter & (Builders<BsonDocument>.Filter.Eq("Status", 3) | Builders<BsonDocument>.Filter.Eq("Status", 4));
var results = collection.Find(filter).ToList();
Dio
  • 21
  • 1
  • 3
0

You could achieve this using the builders and linq if you are strongly typed, otherwise you can use the same builders but provide text instead (these are commended out below the strongly typed queries). You can replace your javascript function with the $exists filter, and you can replace your $or with $in

Something like this should work for you

var builder = Builders<YourModel>.Filter;

var fieldExists = builder.Exists(x => x.Settings.TranslationMemoryId);
//var fieldExists = builder.Exists("TranslationMemoryId");
var statusFilter = builder.In(x => x.Status, new[] { 3, 4 });
//var statusFilter = builder.In("Status", new[] { 3, 4 });
var transIdFilter = builder.Eq(x => x.TranslationMemoryId, "606d7afb-3dce-4533-8f8d-6411715e5b47");
//var transIdFilter = builder.Eq("TranslationMemoryId", "606d7afb-3dce-4533-8f8d-6411715e5b47");

var query = builder.And(builder.And(fieldExists, transIdFilter), statusFilter);

var results = db.getCollection("BackgroundTasks")
    .Find(query)
    .ToList();
pieperu
  • 2,662
  • 3
  • 18
  • 31