mongodb 使用C#聚合Pipeline Atlas搜索阶段

mgdq6dx1  于 2023-04-29  发布在  Go
关注(0)|答案(2)|浏览(135)

我需要使用C#进行此查询:

{
$search:{
{
  range:{
    path:"canvasAi.publication_date",
    gte:ISODate("2021-04-01T00:00:00Z"),
    lte:ISODate("2021-10-11T19:11:16.1928297Z")
  }
}
}
}

到目前为止我有这个:

var query = new JObject(
                    new JProperty("$search", new JObject(
                            new JProperty("range", new JObject(
                                    new JProperty("path", "canvasAi.publication_date"),
                                    new JProperty("gte", "ISODate('2021-04-01T00:00:00Z')"),
                                    new JProperty("lte", "ISODate('2021-10-11T19:11:16.1928297Z')")
                                ))
                        ))
                );

            var new_query = JsonConvert.SerializeObject(query);

var pipeline = new BsonDocument[]
            {
                BsonDocument.Parse(new_query)
            };
var result = collection.Aggregate<BsonDocument>(pipeline);

我一直从mongo得到错误,lte必须是一个数字,日期。
我有画布。publication_date使用Atlas Search索引,并且该字段是上面字符串中给予的格式的字符串。
我已经试了几个小时了,找不到一个方法来进行这个查询。

wgeznvg7

wgeznvg71#

看起来,由于某种原因,LTE日期未被识别。尝试使用BsonDocument表单:

var query = new BsonDocument
    {
        { 
            "$search",
            new BsonDocument
            {
                {
                    "range",
                    new BsonDocument
                    {
                        { "path", "canvasAi.publication_date" },
                        { "gte", DateTime.Parse("2021-04-01T00:00:00Z") },
                        { "lte", DateTime.Parse("2021-10-11T19:11:16.1928297Z") }
                    }
                }
            }
        }
    };
r6l8ljro

r6l8ljro2#

你可以参考博客https://www.c-sharpcorner.com/blogs/mongodb-atlas-search-index-in-c-sharp-build-aggregation-pipeline-with-con

var searchStage = @ "{$search: {index:'" + Constant.SEARCH_INDEX + "'," + searchBy + ": {query:'" + SearchKeyword + "', path:" + Constant.SEARCH_PATH + "}}}";
          var pipeline = new EmptyPipelineDefinition < CollectionRecord > ()
            .AppendStage < CollectionRecord, CollectionRecord, CollectionRecord > (searchStage)
            .Match(PanelFilter);

After defining the stages in a string format, we can have a pipeline definition and execute by calling aggregate method.

entities = await _collectionRepository.AggregateAsync(search.Pipline, search.Sort, search.Projection);
//Some code

public Task<List<CollectionRecord>> AggregateAsync(PipelineDefinition<CollectionRecord, CollectionRecord> pipeline,
  SortDefinition<CollectionRecord> sortDefinition = null, ProjectionDefinition<CollectionRecord, CollectionRecord> projection = null)
{

  if (projection != null && sortDefinition != null)
    pipeline = pipeline.Sort(sortDefinition).Project(projection);

  else if (projection != null)
    pipeline = pipeline.Project(projection);

  return Collection.Aggregate(pipeline).ToListAsync();
}

相关问题