最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

MongoDB使用引用的示例

 更新時(shí)間:2026年03月17日 10:21:47   作者:Victor356  
在MongoDB中,引用(Reference)是一種在文檔之間建立關(guān)系的方式,與嵌入式文檔不同,引用是通過(guò)存儲(chǔ)其他集合中文檔的標(biāo)識(shí)符來(lái)建立關(guān)系,這種方式類似于SQL中的外鍵,適用于需要多個(gè)獨(dú)立集合之間,本文介紹MongoDB什么是引用,感興趣的朋友跟隨小編一起看看吧

在MongoDB中,引用(Reference)是一種在文檔之間建立關(guān)系的方式。與嵌入式文檔不同,引用是通過(guò)存儲(chǔ)其他集合中文檔的標(biāo)識(shí)符來(lái)建立關(guān)系。這種方式類似于SQL中的外鍵,適用于需要多個(gè)獨(dú)立集合之間建立關(guān)系的場(chǎng)景。

引用的特點(diǎn)

  • 分離數(shù)據(jù):引用將相關(guān)數(shù)據(jù)分離到不同的集合中,有助于減少數(shù)據(jù)冗余。
  • 獨(dú)立更新:引用允許獨(dú)立更新相關(guān)數(shù)據(jù),而不需要更新整個(gè)文檔。
  • 適合一對(duì)多和多對(duì)多關(guān)系:引用特別適用于復(fù)雜的數(shù)據(jù)模型,比如一對(duì)多和多對(duì)多關(guān)系。

使用引用的示例

以下示例展示了如何在MongoDB中使用引用。我們將使用Node.js和MongoDB的驅(qū)動(dòng)進(jìn)行操作。

安裝MongoDB的Node.js驅(qū)動(dòng)

npm install mongodb

插入包含引用的數(shù)據(jù)

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({}); // 清空訂單集合
        // 插入用戶數(shù)據(jù)
        const users = await usersCollection.insertMany([
            { name: "Alice" },
            { name: "Bob" },
            { name: "Charlie" }
        ]);
        // 插入訂單數(shù)據(jù),并使用用戶的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 集合中的每個(gè)文檔都包含一個(gè) userId 字段,該字段引用了 users 集合中的用戶文檔的 _id

查詢包含引用的數(shù)據(jù)

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');
        // 查詢某個(gè)用戶及其所有訂單
        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 });
        // 查詢所有訂單及其對(duì)應(yīng)的用戶信息
        console.log("\nQuery all orders and their corresponding users:");
        let results = await ordersCollection.aggregate([
            {
                $lookup: {
                    from: 'users',  // 要關(guān)聯(lián)的集合
                    localField: 'userId',  // orders 集合中的字段
                    foreignField: '_id',  // users 集合中的字段
                    as: 'user'  // 輸出數(shù)組字段
                }
            },
            {
                $unwind: '$user'  // 展開(kāi)數(shù)組
            }
        ]).toArray();
        console.log(results);
    } finally {
        await client.close();
    }
}
queryData().catch(console.error);

在這個(gè)示例中,我們演示了如何查詢包含引用的數(shù)據(jù):

  1. 查詢某個(gè)用戶及其所有訂單。
  2. 查詢所有訂單及其對(duì)應(yīng)的用戶信息。

運(yùn)行這個(gè)腳本后,你會(huì)得到如下結(jié)果(示例輸出):

// 查詢某個(gè)用戶及其所有訂單
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 }
  ]
}
// 查詢所有訂單及其對(duì)應(yīng)的用戶信息
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' }
  }
]

其他語(yǔ)言示例

類似的操作可以在其他編程語(yǔ)言中實(shí)現(xiàn),如Python。以下是Python的示例代碼:

安裝PyMongo

在終端中運(yùn)行以下命令來(lái)安裝PyMongo:

pip install pymongo

插入數(shù)據(jù)

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({})  # 清空訂單集合
    # 插入用戶數(shù)據(jù)
    users = users_collection.insert_many([
        { "name": "Alice" },
        { "name": "Bob" },
        { "name": "Charlie" }
    ])
    # 插入訂單數(shù)據(jù),并使用用戶的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()

查詢數(shù)據(jù)

def query_data():
    client = MongoClient('mongodb://localhost:27017/')
    db = client['myDatabase']
    users_collection = db['users']
    orders_collection = db['orders']
    # 查詢某個(gè)用戶及其所有訂單
    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 })
    # 查詢所有訂單及其對(duì)應(yīng)的用戶信息
    print("\nQuery all orders and their corresponding users:")
    pipeline = [
        {
            '$lookup': {
                'from': 'users',  # 要關(guān)聯(lián)的集合
                'localField': 'userId',  # orders 集合中的字段
                'foreignField': '_id',  # users 集合中的字段
                'as': 'user'  # 輸出數(shù)組字段
            }
        },
        {
            '$unwind': '$user'  # 展開(kāi)數(shù)組
        }
    ]
    results = list(orders_collection.aggregate(pipeline))
    for result in results:
        print(result)
query_data()

到此這篇關(guān)于MongoDB使用引用的示例的文章就介紹到這了,更多相關(guān)MongoDB使用引用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • MongoDB安裝圖文教程

    MongoDB安裝圖文教程

    這篇文章主要為大家詳細(xì)介紹了MongoDB安裝圖文教程,分為兩大部分為大家介紹下載MongoDB和安裝MongoDB的方法,感興趣的小伙伴們可以參考一下
    2016-07-07
  • centos7安裝mongo數(shù)據(jù)庫(kù)的方法(mongo4.2.8)

    centos7安裝mongo數(shù)據(jù)庫(kù)的方法(mongo4.2.8)

    這篇文章給大家介紹了centos7安裝mongo4.2.8數(shù)據(jù)庫(kù)的詳細(xì)過(guò)程,包括mongo數(shù)據(jù)庫(kù)安裝和啟動(dòng)方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2022-01-01
  • MongoDB增刪查改操作示例【基于JavaScript Shell】

    MongoDB增刪查改操作示例【基于JavaScript Shell】

    這篇文章主要介紹了MongoDB增刪查改操作,結(jié)合實(shí)例形式分析了MongoDB數(shù)據(jù)庫(kù)基于JavaScript Shell的基本增刪查改操作技巧與使用注意事項(xiàng),需要的朋友可以參考下
    2019-07-07
  • MongoDB中唯一索引(Unique)的那些事

    MongoDB中唯一索引(Unique)的那些事

    這篇文章主要給大家介紹了關(guān)于MongoDB中唯一索引(Unique)的那些事,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01
  • MongoDB中的Primary Shard詳解

    MongoDB中的Primary Shard詳解

    在MongoDB的Sharding架構(gòu)中,每個(gè)database中都可以存儲(chǔ)兩種類型的集合,一種是未分片的集合,一種是通過(guò)分片鍵,被打散的集合,下面給大家介紹MongoDB中的Primary Shard詳解,感興趣的朋友跟隨小編一起看看吧
    2024-08-08
  • springboot整合mongodb

    springboot整合mongodb

    這篇文章主要介紹了springboot如何整合mongodb,mongodb的安裝和使用,感興趣的同學(xué)可以參考閱讀本文
    2023-03-03
  • MongoDB系列教程(三):Windows中下載和安裝MongoDB

    MongoDB系列教程(三):Windows中下載和安裝MongoDB

    這篇文章主要介紹了MongoDB系列教程(三):MongoDB下載和安裝,本文講解使用Windows環(huán)境安裝MongoDB,需要的朋友可以參考下
    2015-05-05
  • MongoDB用戶管理授權(quán)方式

    MongoDB用戶管理授權(quán)方式

    本文介紹了MongoDB角色類型及其授權(quán)模式,包括單個(gè)數(shù)據(jù)庫(kù)、多個(gè)數(shù)據(jù)庫(kù)、指定單個(gè)數(shù)據(jù)庫(kù)等授權(quán)方式,并提供了授權(quán)命令示例,注意新用戶需要在指定數(shù)據(jù)庫(kù)中創(chuàng)建,并且授權(quán)模式影響登錄串的指定方式
    2026-04-04
  • 淺談MongoDB內(nèi)部的存儲(chǔ)原理

    淺談MongoDB內(nèi)部的存儲(chǔ)原理

    這篇文章主要介紹了淺談MongoDB內(nèi)部的存儲(chǔ)原理,MongoDB是一個(gè)面向文檔的數(shù)據(jù)庫(kù)系統(tǒng)。使用C++編寫,不支持SQL,但有自己功能強(qiáng)大的查詢語(yǔ)法,需要的朋友可以參考下
    2023-07-07
  • MongoDB下根據(jù)數(shù)組大小進(jìn)行查詢的方法

    MongoDB下根據(jù)數(shù)組大小進(jìn)行查詢的方法

    這篇文章主要介紹了MongoDB下根據(jù)數(shù)組大小進(jìn)行查詢的方法,分別實(shí)現(xiàn)了指定大小的數(shù)組和某個(gè)范圍的數(shù)組,需要的朋友可以參考下
    2014-04-04

最新評(píng)論

铜川市| 桃源县| 固始县| 曲靖市| 梁河县| 方城县| 永泰县| 香河县| 饶河县| 兴山县| 怀柔区| 祁连县| 邳州市| 石门县| 宾川县| 大埔区| 鸡东县| 曲阜市| 社会| 铜鼓县| 丰原市| 武穴市| 平江县| 宜君县| 仁布县| 江口县| 大荔县| 锡林浩特市| 会同县| 海林市| 通榆县| 门源| 东乡族自治县| 昭苏县| 新密市| 莆田市| 龙州县| 繁昌县| 疏附县| 如东县| 巴林右旗|