如何在MongoDB中按关键字进行正则表达式匹配,并使用C#将结果按最相关的结果排序?

时间:2019-03-15 16:44:29

标签: c# mongodb mongodb-query mongodb-.net-driver bson

我正则表达式使用C#从Mongo DB的集合[Brands]之一中的字段[Name]中搜索一个{keyword}。结果项将由textMatchScore降序排序。结果看起来不错,但格式看起来很奇怪。

  

预期结果将是这样。

[
    {
        "id": "5c8bcbc36ad6840725182158",
        "name": "Window XP",
        "dateAdded": "2019-03-15T15:58:58.925Z"
    },
    {
        "id": "5c8bcbc96ad6840725182159",
        "name": "Wind",
        "dateAdded": "2019-03-15T15:59:05.429Z"
    },
    {
        "id": "5c8bcbd16ad684072518215a",
        "name": "Wired",
        "dateAdded": "2019-03-15T15:59:13.292Z"
    }
]
  

这是实际结果。

[
    [
        {
            "name": "_id",
            "value": "5c8bcbc36ad6840725182158"
        },
        {
            "name": "Name",
            "value": "Window XP"
        },
        {
            "name": "DateAdded",
            "value": "2019-03-15T15:58:58.925Z"
        },
        {
            "name": "textMatchScore",
            "value": 0
        }
    ],
    [
        {
            "name": "_id",
            "value": "5c8bcbc96ad6840725182159"
        },
        {
            "name": "Name",
            "value": "Wind"
        },
        {
            "name": "DateAdded",
            "value": "2019-03-15T15:59:05.429Z"
        },
        {
            "name": "textMatchScore",
            "value": 0
        }
    ]
]
  

这是C#零件代码。

[HttpGet]
public async Task<IActionResult> QueryAsync([FromQuery]string q, [FromQuery]int limit = 10, [FromQuery]int skip = 0)
{
    var mongoUrl = new MongoUrl(_mongoConfig.ConnectionString);
    var client = new MongoClient(mongoUrl);
    var database = client.GetDatabase(mongoUrl.DatabaseName);
    var collection = database.GetCollection<Brand>("Brands");

    var regex = new BsonRegularExpression($".*{q}.*","i");

    var filter = Builders<Brand>.Filter.Regex("Name", regex);
    var projection = Builders<Brand>.Projection.MetaTextScore("textMatchScore");
    var sort = Builders<Brand>.Sort.MetaTextScore("textMatchScore");

    var result = await collection.Find(filter).Project(projection).Sort(sort).Skip(skip).Limit(limit).ToListAsync();

    return Ok(result);
}

enter image description here enter image description here

  

查询是否已正确实施?而且,我该怎么做才能使结果格式成为相当整洁的json格式?

0 个答案:

没有答案