有这样的文件:
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
我如何查询grades.date.year = 2016?
正在尝试:
var filter = Builders<BsonDocument>.Filter.Eq("grades.date.year", 2016);
var result = await collection.Find(filter).ToListAsync();
但我想点符号只适用于json doc,而不是对象?搜索互联网,但找不到一个干净的例子。
编辑:C#类?class Address
{
public string street { get; set; }
public string zipcode { get; set; }
public string building { get; set; }
public IEnumerable<double> coord { get; set; }
}
class Grade
{
public DateTime date { get; set; }
public string grade { get; set; }
public int score { get; set; }
}
class TestX
{
public ObjectId _id { get; set; }
public Address address { get; set; }
public string borough { get; set; }
public string cuisine { get; set; }
public IEnumerable<Grade> grades { get; set; }
public string name { get; set; }
public string restaurant_id { get; set; }
}
答案 0 :(得分:1)
这需要聚合框架。 如果您可以发布c#类,那么将更新我对强类型c#的回答,但现在决定在项目阶段内预测项目年度。
public static void Main()
{
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("hammer");
var project =
BsonDocument.Parse(
"{_id: 1,address: 1,borough: 1,cuisine: 1,grades: 1,name: 1,restaurant_id: 1,year: {$year: '$grades.date'}}");
var aggregationDocument =
collection.Aggregate()
.Unwind("grades")
.Project(project)
.Match(BsonDocument.Parse("{'year' : {$in : [2013, 2015]}}"))
.ToList();
foreach (var result in aggregationDocument)
{
Console.WriteLine(result.ToString());
}
Console.ReadLine();
}
var aggregationDocument =
collection.Aggregate<TestX>()
.Unwind<TestX>(x=>x.grades)
.Match(BsonDocument.Parse(
"{$and:[{'grades.date':{$gte: ISODate('2012-01-01')}},{'grades.date':{$lt: ISODate('2013-01-01')}}]}"))
.ToList();
答案 1 :(得分:-1)
另一种方法是检查日期是否在该年内。
I.e for 2016使用$gte: 2016-01-01 00:00:00
和$lt: 2017-01-01 00:00:00
Find objects between two dates MongoDB
c#中可能包含Gte
和Lt
的功能。可能有一些简单的方法来组合过滤器,如&
或类似的。