gpt4 book ai didi

c# - 如何在 C# 中为以下 MongoDB 查询场景编写搜索查询

转载 作者:可可西里 更新时间:2023-11-01 10:48:52 26 4
gpt4 key购买 nike

考虑以下 5 个参数:

  1. 共同的 friend
  2. 家乡
  3. 当前城市
  4. 学校
  5. 公司

我需要编写一个搜索查询,搜索应该从匹配所有参数开始,这样才能获得准确的结果。

  • 考虑至少 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"));

最佳答案

使用聚合实现它的方法是:

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();

关于c# - 如何在 C# 中为以下 MongoDB 查询场景编写搜索查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45769415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com