Nodejs mongodb 内嵌文档查询

Nodejs mongodb 内嵌文档查询

{ “shellList”: [ { “bookId”: “168”, “readPagePercent”: “0”, “createTime”: “2014-01-21 16:17:33”, “readType”: “1” }, { “bookId”: “168”, “readPagePercent”: “2”, “createTime”: “2014-02-21 16:17:33”, “readType”: “2” } , { “bookId”: “169”, “readPagePercent”: “2”, “createTime”: “2014-02-21 16:17:33”, “readType”: “2” } , { “bookId”: “170”, “readPagePercent”: “2”, “createTime”: “2014-02-21 16:17:33”, “readType”: “2” } ], “userId”: “100002” } 我怎查出 bookid为168的文档呢 求指导


3 回复

当然可以!为了查询内嵌文档(例如 bookId 为 “168” 的文档),我们可以使用 Node.js 和 MongoDB 的查询功能。下面是一个简单的示例,展示如何进行这样的查询。

首先,确保你已经安装了 MongoDB 的 Node.js 驱动程序。你可以通过以下命令来安装:

npm install mongodb

接下来,我们将编写一个简单的示例来查询 bookId 为 “168” 的文档。

示例代码

const { MongoClient } = require('mongodb');

async function run() {
    const uri = 'your_mongodb_connection_string'; // 替换为你的 MongoDB 连接字符串
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        await client.connect();
        const database = client.db('your_database_name'); // 替换为你的数据库名称
        const collection = database.collection('your_collection_name'); // 替换为你的集合名称

        // 查询 bookId 为 "168" 的文档
        const query = { shellList: { $elemMatch: { bookId: "168" } } };
        
        const result = await collection.find(query).toArray();

        console.log(result);
    } catch (err) {
        console.error(err.stack);
    } finally {
        await client.close();
    }
}

run().catch(console.dir);

解释

  1. 连接到 MongoDB:

    • 使用 MongoClient 创建一个到 MongoDB 的连接。
    • uri 是你的 MongoDB 数据库的连接字符串。
  2. 选择数据库和集合:

    • 使用 client.db() 方法选择数据库。
    • 使用 database.collection() 方法选择集合。
  3. 构建查询:

    • 我们使用 $elemMatch 操作符来匹配数组中的元素。在这个例子中,我们查找 shellList 数组中 bookId 等于 “168” 的文档。
    • query 对象如下:
      const query = { shellList: { $elemMatch: { bookId: "168" } } };
      
  4. 执行查询:

    • 使用 collection.find(query).toArray() 方法执行查询,并将结果转换为数组。
  5. 输出结果:

    • 将查询结果打印到控制台。

希望这能帮助你查询 bookId 为 “168” 的文档。如果有任何问题或需要进一步的帮助,请随时告诉我!


db.collection.find({},{‘shellList’:{$elemMatch:{‘bookId’:‘168’}}})只能查出一条 但是我希望符合条件的都查出来,好诡异的查询。 mongodb 有个$slice ,可以把数组劈开,既然这样可以,那应该有条件查询相关的解决方法

要在 Node.js 中使用 MongoDB 查询内嵌文档,你可以使用 Mongoose 或原生的 MongoDB 驱动。以下是使用 Mongoose 的示例代码来查询 bookId168 的文档。

假设你有一个名为 User 的 Mongoose 模型,并且 shellList 是该模型中的一个数组字段:

const mongoose = require('mongoose');

// 假设这是你的 User 模型定义
const userSchema = new mongoose.Schema({
    userId: String,
    shellList: [{
        bookId: String,
        readPagePercent: Number,
        createTime: Date,
        readType: String
    }]
});

const User = mongoose.model('User', userSchema);

async function findUserByBookId(bookId) {
    try {
        const result = await User.findOne({ 'shellList.bookId': bookId });
        if (result) {
            console.log(result);
        } else {
            console.log("No document found with the specified bookId.");
        }
    } catch (error) {
        console.error("Error querying the database:", error);
    }
}

findUserByBookId('168');

解释:

  1. Mongoose 模型:首先定义了一个 User 模型,其中包含 shellList 数组。
  2. 查询函数findUserByBookId 函数用于查询 shellList 数组中 bookId 为指定值的文档。
  3. findOne 方法findOne 方法用于查询符合指定条件的第一个文档。这里我们使用对象 { 'shellList.bookId': bookId } 来指定查询条件,表示查询 shellList 数组中任何元素的 bookId 等于指定的 bookId

通过这种方式,你可以轻松地查询内嵌文档中的特定字段。

回到顶部