【问题标题】:MongoDB query two collections with sort ordersMongoDB 使用排序顺序查询两个集合
【发布时间】:2016-08-30 16:41:42
【问题描述】:

示例:让我们假设以下集合。 ThrashMetalDocumentsCollection 和 SpeedMetalDocumentsCollection,这两个集合具有相同的 HeavyMetalRecordDocument 结构,如下所示。如何查询并返回两个集合中的所有记录并按 releaseDate(最早的优先)和评级(从高到低)对它们进行排序?谢谢! \m/ \m/

static async Task getAllRecords()
{
    var builder = Builders<HeavyMetalRecordDocument>.Filter;
    //var filter;

    using (var cursor = await ThrashMetalDocumentsCollection.Find()
    .Sort(Builders<HeavyMetalRecordDocument>.Sort.Ascending(x => x.rating))
    .ToCursorAsync()) 
    {
        while (await cursor.MoveNextAsync())
        {
            foreach (var doc in cursor.Current)
            {
                //Do Something…
            }
        }
    }
}

public class HeavyMetalRecordDocument
{
    public ObjectId Id { get; set; }
    public String artist { get; set; }
    public String title { get; set; }
    public DateTime releaseDate { get; set; }
    public int rating { get; set; } // 1-10
}

【问题讨论】:

  • 看看mongodb $lookup 操作符

标签: mongodb-query mongodb-.net-driver


【解决方案1】:

MongoDB 不是关系数据库,因此,它无法执行连接(这是您想要完成的任务)。您可能想更多地考虑数据库的结构。在不知道您要做什么的情况下,我建议将所有类型的专辑放在一个集合中 - 放置一个指示专辑流派的附加字段。

【讨论】:

  • 我会做一些小的调整,并将范围限制在一个集合中。谢谢!
猜你喜欢
  • 2016-05-02
  • 1970-01-01
  • 2020-03-24
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多