如何在C#中为下面的MongoDB查询场景编写搜索查询

时间:2017-08-19 08:27:51

标签: c# mongodb mongodb-query nosql

考虑以下5个参数:

  1. 相互朋友
  2. 家乡
  3. 当前城市
  4. 学校
  5. 公司
  6. 我需要编写一个搜索查询,搜索应该从匹配所有参数开始,这将获得准确的结果。

    • 考虑至少4个参数
    • 如果没有,则考虑至少3个参数
    • 如果没有,则考虑至少2个参数
    • 如果没有,则考虑至少1个参数
    • 如果没有则显示全部。

    如何在C#中为上述场景编写搜索查询?

    我使用了以下代码

    public class UserDetails
        {
            [BsonId]
            [BsonRepresentation(BsonType.ObjectId)]
            public string _id { get; set; }
            public string UserId { get; set; }
            public Registration RegistrationDetails { get; set; }
         }
    public class Registration
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    var collection = database.GetCollection<UserDetails>("UserInfo");
                    var agg = collection.Aggregate().Project(p => new
                    {
                        p.Id,
                        matchValue =
                        (p.RegistrationDetails.FirstName == search ? 1 : 0) +
                        (p.RegistrationDetails.LastName == search ? 1 : 0)
                    })
                    .Group(new BsonDocument(new Dictionary<string, BsonValue>
                    {
                        {"_id", BsonValue.Create("$matchValue")},
                        {"ids", new BsonDocument("$push", new 
                         BsonDocument("item","$Id"))}
                    }))
                    .Sort(new BsonDocument("_id", BsonValue.Create(-1)))
                    .Limit(1)
                    .Unwind("ids")
                    .Project(new BsonDocument("_id", "$ids.item"));
    

1 个答案:

答案 0 :(得分:0)

使用 Aggregate 实现它的方法是:

var sr = new MongoClient("mongodb://127.0.0.1");
var db = sr.GetDatabase("Test");
var col = db.GetCollection<User>("MyUser");

var agg = col.Aggregate()
    .Project(p => new
    {
        p.Id,
        matchValue =
            (p.HomeTown == "Town 1" ? 1 : 0) +       // HomeTown condition
            (p.CurrentCity == "City 1" ? 1 : 0) +    // CurrentCity condition
            (p.School == "School 1" ? 1 : 0) +       // School condition
            (p.Company == "Company 1" ? 1 : 0)       // Company condition
        // matchValue will contains count of equal fields
    })
    .Group(new BsonDocument(new Dictionary<string, BsonValue>
    {
        {"_id", BsonValue.Create("$matchValue")},
        {"ids", new BsonDocument("$push", new BsonDocument("item","$Id")) }
        // Now I aggregate ids based on `matchValue`
    }))
    .Sort(new BsonDocument("_id", BsonValue.Create(-1)))
    .Limit(1)
    // Now I have maximum `matchValue` 
    .Unwind("ids")
    .Project(new BsonDocument("_id", "$ids.item"));
    // Now ids are available

// To gathering results I used below code:
var result = agg.ToList().Select(c=> c["_id"].AsObjectId).ToList();