it编程 > 数据库 > mongodb

MongoDB使用引用的示例

4人参与 2026-03-17 mongodb

在mongodb中,引用(reference)是一种在文档之间建立关系的方式。与嵌入式文档不同,引用是通过存储其他集合中文档的标识符来建立关系。这种方式类似于sql中的外键,适用于需要多个独立集合之间建立关系的场景。

引用的特点

使用引用的示例

以下示例展示了如何在mongodb中使用引用。我们将使用node.js和mongodb的驱动进行操作。

安装mongodb的node.js驱动

npm install mongodb

插入包含引用的数据

const { mongoclient, objectid } = require('mongodb');
async function insertdata() {
    const uri = "mongodb://localhost:27017";
    const client = new mongoclient(uri, { useunifiedtopology: true });
    try {
        await client.connect();
        const db = client.db('mydatabase');
        const userscollection = db.collection('users');
        const orderscollection = db.collection('orders');
        await userscollection.deletemany({}); // 清空用户集合
        await orderscollection.deletemany({}); // 清空订单集合
        // 插入用户数据
        const users = await userscollection.insertmany([
            { name: "alice" },
            { name: "bob" },
            { name: "charlie" }
        ]);
        // 插入订单数据,并使用用户的objectid作为引用
        await orderscollection.insertmany([
            { userid: users.insertedids[0], amount: 50.5, date: new date("2022-01-01") },
            { userid: users.insertedids[0], amount: 100.0, date: new date("2022-02-01") },
            { userid: users.insertedids[1], amount: 75.0, date: new date("2022-01-15") },
            { userid: users.insertedids[2], amount: 200.0, date: new date("2022-03-01") }
        ]);
        console.log("data inserted");
    } finally {
        await client.close();
    }
}
insertdata().catch(console.error);

在上面的代码中,orders 集合中的每个文档都包含一个 userid 字段,该字段引用了 users 集合中的用户文档的 _id

查询包含引用的数据

async function querydata() {
    const uri = "mongodb://localhost:27017";
    const client = new mongoclient(uri, { useunifiedtopology: true });
    try {
        await client.connect();
        const db = client.db('mydatabase');
        const userscollection = db.collection('users');
        const orderscollection = db.collection('orders');
        // 查询某个用户及其所有订单
        console.log("\nquery a user and their orders:");
        let user = await userscollection.findone({ name: "alice" });
        let orders = await orderscollection.find({ userid: user._id }).toarray();
        console.log({ user, orders });
        // 查询所有订单及其对应的用户信息
        console.log("\nquery all orders and their corresponding users:");
        let results = await orderscollection.aggregate([
            {
                $lookup: {
                    from: 'users',  // 要关联的集合
                    localfield: 'userid',  // orders 集合中的字段
                    foreignfield: '_id',  // users 集合中的字段
                    as: 'user'  // 输出数组字段
                }
            },
            {
                $unwind: '$user'  // 展开数组
            }
        ]).toarray();
        console.log(results);
    } finally {
        await client.close();
    }
}
querydata().catch(console.error);

在这个示例中,我们演示了如何查询包含引用的数据:

  1. 查询某个用户及其所有订单
  2. 查询所有订单及其对应的用户信息

运行这个脚本后,你会得到如下结果(示例输出):

// 查询某个用户及其所有订单
query a user and their orders:
{
  user: { _id: new objectid("..."), name: 'alice' },
  orders: [
    { _id: new objectid("..."), userid: new objectid("..."), amount: 50.5, date: 2022-01-01t00:00:00.000z },
    { _id: new objectid("..."), userid: new objectid("..."), amount: 100, date: 2022-02-01t00:00:00.000z }
  ]
}
// 查询所有订单及其对应的用户信息
query all orders and their corresponding users:
[
  {
    _id: new objectid("..."),
    userid: new objectid("..."),
    amount: 50.5,
    date: 2022-01-01t00:00:00.000z,
    user: { _id: new objectid("..."), name: 'alice' }
  },
  {
    _id: new objectid("..."),
    userid: new objectid("..."),
    amount: 100,
    date: 2022-02-01t00:00:00.000z,
    user: { _id: new objectid("..."), name: 'alice' }
  },
  {
    _id: new objectid("..."),
    userid: new objectid("..."),
    amount: 75,
    date: 2022-01-15t00:00:00.000z,
    user: { _id: new objectid("..."), name: 'bob' }
  },
  {
    _id: new objectid("..."),
    userid: new objectid("..."),
    amount: 200,
    date: 2022-03-01t00:00:00.000z,
    user: { _id: new objectid("..."), name: 'charlie' }
  }
]

其他语言示例

类似的操作可以在其他编程语言中实现,如python。以下是python的示例代码:

安装pymongo

在终端中运行以下命令来安装pymongo:

pip install pymongo

插入数据

from pymongo import mongoclient
from datetime import datetime
def insert_data():
    client = mongoclient('mongodb://localhost:27017/')
    db = client['mydatabase']
    users_collection = db['users']
    orders_collection = db['orders']
    users_collection.delete_many({})  # 清空用户集合
    orders_collection.delete_many({})  # 清空订单集合
    # 插入用户数据
    users = users_collection.insert_many([
        { "name": "alice" },
        { "name": "bob" },
        { "name": "charlie" }
    ])
    # 插入订单数据,并使用用户的objectid作为引用
    orders_collection.insert_many([
        { "userid": users.inserted_ids[0], "amount": 50.5, "date": datetime(2022, 1, 1) },
        { "userid": users.inserted_ids[0], "amount": 100.0, "date": datetime(2022, 2, 1) },
        { "userid": users.inserted_ids[1], "amount": 75.0, "date": datetime(2022, 1, 15) },
        { "userid": users.inserted_ids[2], "amount": 200.0, "date": datetime(2022, 3, 1) }
    ])
    print("data inserted")
insert_data()

查询数据

def query_data():
    client = mongoclient('mongodb://localhost:27017/')
    db = client['mydatabase']
    users_collection = db['users']
    orders_collection = db['orders']
    # 查询某个用户及其所有订单
    print("\nquery a user and their orders:")
    user = users_collection.find_one({ "name": "alice" })
    orders = list(orders_collection.find({ "userid": user['_id'] }))
    print({ "user": user, "orders": orders })
    # 查询所有订单及其对应的用户信息
    print("\nquery all orders and their corresponding users:")
    pipeline = [
        {
            '$lookup': {
                'from': 'users',  # 要关联的集合
                'localfield': 'userid',  # orders 集合中的字段
                'foreignfield': '_id',  # users 集合中的字段
                'as': 'user'  # 输出数组字段
            }
        },
        {
            '$unwind': '$user'  # 展开数组
        }
    ]
    results = list(orders_collection.aggregate(pipeline))
    for result in results:
        print(result)
query_data()

到此这篇关于mongodb使用引用的示例的文章就介绍到这了,更多相关mongodb使用引用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

MongoDB大规模数据索引创建的性能调优与时间优化全指南

03-05

MongoDB索引统计分析db.collection.stats()深度解读与应用方案

03-05

MongoDB索引优化之识别并消除索引冗余的实用方法

03-03

MongoDB使用更新操作符set与unset精准修改与删除字段

03-02

MongoDB分组查询、聚合查询实例

03-02

MongoDB存储路径的配置指南

02-28

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论