MongoDB 中的关系(使用 .Net)

Inx*_*x51 5 .net c# 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 来建立关系。然而..这是否也意味着对于每个关系,您还需要执行一个额外的查询?..

mic*_*ckl 6

考虑如下最简单的关系:

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"
})
Run Code Online (Sandbox Code Playgroud)

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

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

返回:

{ 
    "_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" } ] 
}
Run Code Online (Sandbox Code Playgroud)

使用 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();
Run Code Online (Sandbox Code Playgroud)

它被转换$lookup$unwind,这样你就得到一个publisher对象而不是数组