我正则表达式使用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);
}
查询是否已正确实施?而且,我该怎么做才能使结果格式成为相当整洁的json格式?