我有一组假装付款的状态,每个都有付款ID。
我想获取每个付款ID的最新状态。测试我创建了一些虚拟数据然后尝试查询它。我到目前为止:
[Test]
public void GetPaymentLatestStatuses()
{
var client = new TestMongoClient();
var database = client.GetDatabase("payments");
var paymentRequestsCollection = database.GetCollection<BsonDocument>("paymentRequests");
var statusesCollection = database.GetCollection<BsonDocument>("statuses");
var payment = new BsonDocument { { "amount", RANDOM.Next(10) } };
paymentRequestsCollection.InsertOne(payment);
var paymentId = payment["_id"];
var receivedStatus = new BsonDocument
{
{ "payment", paymentId },
{ "code", "received" },
{ "date", DateTime.UtcNow }
};
var acceptedStatus = new BsonDocument
{
{ "payment", paymentId },
{ "code", "accepted" },
{ "date", DateTime.UtcNow.AddSeconds(-1) }
};
var completedStatus = new BsonDocument
{
{ "payment", paymentId },
{ "code", "completed" },
{ "date", DateTime.UtcNow.AddSeconds(-2) }
};
statusesCollection.InsertMany(new [] { receivedStatus, acceptedStatus, completedStatus });
var groupByPayments = new BsonDocument { {"_id", "$payment"} };
var statuses = statusesCollection.Aggregate().Group(groupByPayments);
}
但现在我在砖墙上。
任何正确的方向戳都会有所帮助。我不确定我是不是在俯视望远镜的错误端。
以下为我提供了正确文件的ID。
var groupByPayments = new BsonDocument
{
{ "_id", "$payment" },
{ "id", new BsonDocument { { "$first", "$_id" } } }
};
var sort = Builders<BsonDocument>.Sort.Descending(document => document["date"]);
var statuses = statusesCollection.Aggregate().Sort(sort).Group(groupByPayments).ToList();
我是否可以使用单个查询获取完整文档,或者我是否必须重新发出命令以获取该列表中的所有文档?
答案 0 :(得分:10)
让我们从简单的方法开始,了解您想要实现的目标。在MongoDB的C#Driver 2.X中,您可以找到AsQueryable
扩展方法,让您从集合中创建LINQ查询。这个Linq提供程序是在MongoDB的Aggregation框架上构建的,所以最后你的链接查询将被转换为聚合管道。所以,如果你有这样一个类:
public class Status
{
public ObjectId _id { get; set; }
public ObjectId payment { get; set; }
public string code { get; set; }
public DateTime date { get; set; }
}
您可以创建如下所示的查询:
var statusesCollection = database.GetCollection<Status>("statuses");
var result= statusesCollection.AsQueryable()
.OrderByDescending(e=>e.date)
.GroupBy(e=>e.payment)
.Select(g=>new Status{_id =g.First()._id,
payment = g.Key,
code=g.First().code,
date=g.First().date
}
)
.ToList();
现在您可能想知道为什么我必须将结果投影到Status
类的新实例,如果我能从每个组中获得相同的结果调用First
扩展方法?不幸的是,这还不支持。其中一个原因是因为Linq提供程序在构建聚合管道时使用$first操作,这就是$first
操作的工作原理。另外,正如您在$first
阶段中使用$group
时在早期共享链接中看到的那样,$group
阶段应遵循$sort
阶段按照定义的顺序输入文档。
现在,假设您不想使用Linq,并且您希望自己创建聚合管道,则可以执行以下操作:
var groupByPayments = new BsonDocument
{
{ "_id", "$payment" },
{ "statusId", new BsonDocument { { "$first", "$_id" } } },
{ "code", new BsonDocument { { "$first", "$code" } } },
{ "date", new BsonDocument { { "$first", "$date" } } }
};
var sort = Builders<BsonDocument>.Sort.Descending(document => document["date"]);
ProjectionDefinition<BsonDocument> projection = new BsonDocument
{
{"payment", "$_id"},
{"id", "$statusId"},
{"code", "$code"},
{"date", "$date"},
};
var statuses = statusesCollection.Aggregate().Sort(sort).Group(groupByPayments).Project(projection).ToList<BsonDocument>();
这个解决方案的优势在于您可以一次性获取数据,缺点是您必须预测所需的所有字段。我的结论是,如果文档没有很多字段,或者您不喜欢不需要你文档中的所有字段我会使用这个变体。
答案 1 :(得分:1)
这就是我实现它的方式。必须有更好的方法。
[Test]
public void GetPaymentLatestStatuses()
{
var client = new TestMongoClient();
var database = client.GetDatabase("payments");
var paymentRequestsCollection = database.GetCollection<BsonDocument>("paymentRequests");
var statusesCollection = database.GetCollection<BsonDocument>("statuses");
var payment = new BsonDocument { { "amount", RANDOM.Next(10) } };
paymentRequestsCollection.InsertOne(payment);
var paymentId = payment["_id"];
var receivedStatus = new BsonDocument
{
{ "payment", paymentId },
{ "code", "received" },
{ "date", DateTime.UtcNow }
};
var acceptedStatus = new BsonDocument
{
{ "payment", paymentId },
{ "code", "accepted" },
{ "date", DateTime.UtcNow.AddSeconds(+1) }
};
var completedStatus = new BsonDocument
{
{ "payment", paymentId },
{ "code", "completed" },
{ "date", DateTime.UtcNow.AddSeconds(+2) }
};
statusesCollection.InsertMany(new[] { receivedStatus, acceptedStatus, completedStatus });
var groupByPayments = new BsonDocument
{
{ "_id", "$payment" },
{ "id", new BsonDocument { { "$first", "$_id" } } }
};
var sort = Builders<BsonDocument>.Sort.Descending(document => document["date"]);
var statuses = statusesCollection.Aggregate().Sort(sort).Group(groupByPayments).ToList();
var statusIds = statuses.Select(x => x["id"]);
var completedStatusDocumentsFilter =
Builders<BsonDocument>.Filter.Where(document => statusIds.Contains(document["_id"]));
var statusDocuments = statusesCollection.Find(completedStatusDocumentsFilter).ToList();
foreach (var status in statusDocuments)
{
Assert.That(status["code"].AsString, Is.EqualTo("completed"));
}
}
答案 2 :(得分:0)
必须有更好的方法。
从2.5.3开始,您可以访问聚合内的当前组。这使我们可以构建一个通用访问器,它将通过本机mongo查询从分组中检索第一个元素。
首先,反序列化的辅助类。 /// <summary>
/// Mongo-ified version of <see cref="KeyValuePair{TKey, TValue}"/>
/// </summary>
class InternalKeyValuePair<T, TKey>
{
[BsonId]
public TKey Key { get; set; }
public T Value { get; set; }
}
//you may not need this method to be completely generic,
//but have the sortkey be the same helps
interface IDateModified
{
DateTime DateAdded { get; set; }
}
private List<T> GroupFromMongo<T,TKey>(string KeyName) where T : IDateModified
{
//mongo linq driver doesn't support this syntax, so we make our own bsondocument. With blackjack. And Hookers.
BsonDocument groupDoc = MongoDB.Bson.BsonDocument.Parse(@"
{
_id: '$" + KeyName + @"',
Value: { '$first': '$$CURRENT' }
}");
//you could use the same bsondocument parsing trick to get a generic
//sorting key as well as a generic grouping key, or you could use
//expressions and lambdas and make it...perfect.
SortDefinition<T> sort = Builders<T>.Sort.Descending(document => document.DateAdded);
List<BsonDocument> intermediateResult = getCol<T>().Aggregate().Sort(sort).Group(groupDoc).ToList();
InternalResult<T, TKey>[] list = intermediateResult.Select(r => MongoDB.Bson.Serialization.BsonSerializer.Deserialize<InternalResult<T, TKey>>(r)).ToArray();
return list.Select(z => z.Value).ToList();
}
已被封存,因此我们自己动手。
/// <summary>
/// Mongo-ified version of <see cref="KeyValuePair{TKey, TValue}"/>
/// </summary>
class MongoKeyValuePair<T, TKey>
{
[BsonId]
public TKey Key { get; set; }
public T Value { get; set; }
}
private MongoKeyValuePair<T, TKey>[] GroupFromMongo<T, TKey>(Expression<Func<T, TKey>> KeySelector, Expression<Func<T, object>> SortSelector)
{
//mongo linq driver doesn't support this syntax, so we make our own bsondocument. With blackjack. And Hookers.
BsonDocument groupDoc = MongoDB.Bson.BsonDocument.Parse(@"
{
_id: '$" + GetPropertyName(KeySelector) + @"',
Value: { '$first': '$$CURRENT' }
}");
SortDefinition<T> sort = Builders<T>.Sort.Descending(SortSelector);
List<BsonDocument> groupedResult = getCol<T>().Aggregate().Sort(sort).Group(groupDoc).ToList();
MongoKeyValuePair<T, TKey>[] deserializedGroupedResult = groupedResult.Select(r => MongoDB.Bson.Serialization.BsonSerializer.Deserialize<MongoKeyValuePair<T, TKey>>(r)).ToArray();
return deserializedGroupedResult;
}
/* This was my original non-generic method with hardcoded strings, PhonesDocument is an abstract class with many implementations */
public List<T> ListPhoneDocNames<T>() where T : PhonesDocument
{
return GroupFromMongo<T,String>(z=>z.FileName,z=>z.DateAdded).Select(z=>z.Value).ToList();
}
public string GetPropertyName<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
return propInfo.Name;
}
好的..我在https://stackoverflow.com/a/672212/346272
的帮助下对其进行了通用化 class MongoKeyValuePair<T, TKey>
{
[BsonId]
public TKey Key { get; set; }
public T Value { get; set; }
public long Count { get; set; }
}
BsonDocument groupDoc = MongoDB.Bson.BsonDocument.Parse(@"
{
_id: '$" + GetPropertyName(KeySelector) + @"',
Value: { '$first': '$$CURRENT' },
Count: { $sum: 1 }
}");
对于奖励积分,您现在可以轻松地执行任何mongos其他分组操作,而无需对抗linq助手。有关所有可用的分组操作,请参阅https://docs.mongodb.com/manual/reference/operator/aggregation/group/。我们加一个计数。
import { Injectable } from '@angular/core';
@Injectable()
export class ErrorService {
errorInfo: string;
}
运行与之前完全相同的聚合,您的count属性将填入与您的groupkey匹配的文档数量。整齐!