MongoDB中的关系(使用.Net)

时间:2019-06-02 11:25:58

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

无论如何,mongoDB中是否都使用.Net创建了某种等效于“ SQL-Join”的东西? 我已经阅读了有关关系的MongoDB文档(https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/)。据我了解,您只需引用关系ID即可添加关系。但是..这是否还意味着对于每种关系,您还需要执行一个附加查询?..

2 个答案:

答案 0 :(得分:1)

考虑最简单的关系,如下所示:

db.publishers.save({
    _id: "oreilly",
    name: "O'Reilly Media",
    founded: 1980,
    location: "CA"
})

db.books.save({
    _id: 123456789,
    title: "MongoDB: The Definitive Guide",
    author: [ "Kristina Chodorow", "Mike Dirolf" ],
    published_date: ISODate("2010-09-24"),
    pages: 216,
    language: "English",
    publisher_id: "oreilly"
})

在MongoDB中,您可以使用$lookup运算符在一个查询中从两个集合中获取数据:

db.books.aggregate([
    {
        $lookup: {
            from: "publishers",
            localField: "publisher_id",
            foreignField: "_id",
            as: "publisher"
        }
    }
])

返回:

{ 
    "_id" : 123456789, 
    "title" : "MongoDB: The Definitive Guide", 
    "author" : [ "Kristina Chodorow", "Mike Dirolf" ], 
    "published_date" : ISODate("2010-09-24T00:00:00Z"), 
    "pages" : 216, 
    "language" : "English", 
    "publisher_id" : "oreilly", 
    "publisher" : [ { "_id" : "oreilly", "name" : "O'Reilly Media", "founded" : 1980, "location" : "CA" } ] 
}

使用MongoDB .NET驱动程序,您可以使用LINQ语法和join运算符,将其转换为$lookup

var books = db.GetCollection<Book>("books");
var publishers = db.GetCollection<Publisher>("publishers");

var q = from book in books.AsQueryable()
        join publisher in publishers.AsQueryable() on
            book.publisher_id equals publisher._id
        select new
        {
            book,
            publisher = publisher
        };

var result = q.ToList();

将其与$unwind转换为$lookup,以便获得单个publisher对象而不是数组

答案 1 :(得分:0)

如果您不介意使用库,则 MongoDB.Entities 可以非常轻松地建立关系,而无需手动进行联接,除非您真的想要:-)

查看下面的代码,该代码演示了作者与书本实体之间的一对多关系。这本书实体对作者一无所知。但您仍然可以通过提供书籍ID,书籍ID的数组甚至是书籍的IQueryable来获得反向关系访问。 [免责声明:我是图书馆的作者]

using System;
using System.Linq;
using MongoDB.Entities;
using MongoDB.Driver.Linq;

namespace StackOverflow
{
    public class Program
    {
        public class Author : Entity
        {
            public string Name { get; set; }
            public Many<Book> Books { get; set; }

            public Author() => this.InitOneToMany(() => Books);
        }

        public class Book : Entity
        {
            public string Title { get; set; }
        }

        static void Main(string[] args)
        {
            new DB("test");

            var book = new Book { Title = "The Power Of Now" };
            book.Save();

            var author = new Author { Name = "Eckhart Tolle" };
            author.Save();

            author.Books.Add(book);

            //build a query for finding all books that has Power in the title.
            var bookQuery = DB.Queryable<Book>()
                              .Where(b => b.Title.Contains("Power"));

            //find all the authors of books that has a title with Power in them
            var authors = author.Books
                                .ParentsQueryable<Author>(bookQuery);

            //get the result
            var result = authors.ToArray();

            //output the aggregation pipeline
            Console.WriteLine(authors.ToString());


            Console.ReadKey();
        }
    }
}