请教,在mongodb的查询中如何使用Nodejs引用文档(记录)中的key值?

请教,在mongodb的查询中如何使用Nodejs引用文档(记录)中的key值?

比如:有如下文档: {a:2,b:3}

如何在查询条件中引用key b的值呢?比如我想做:

find({a:{$gt:b+1}}),但是这样,会提示b没有定义,当然这个例子可以用$where去实现。

但是我只是想知道如何引用b的值,谢谢!

7 回复

在MongoDB的查询中,如果你想引用文档(记录)中的key值,可以通过访问该文档的属性来实现。你可以在Node.js中使用Mongoose库来处理这种需求,Mongoose是一个对象模型工具,它封装了MongoDB的驱动程序,并提供了一些高级功能,如模式验证、查询构建器等。

以下是如何在Node.js中引用文档中的key值并进行查询的示例:

示例文档结构

假设我们有一个集合documents,其中包含以下文档:

{
  "_id": ObjectId("..."),
  "a": 2,
  "b": 3
}

使用Mongoose进行查询

首先,确保你已经安装了Mongoose库。如果没有安装,可以使用npm安装:

npm install mongoose

然后,你可以创建一个Mongoose模型,并使用该模型进行查询。以下是具体的步骤和代码示例:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 定义Schema
const documentSchema = new Schema({
  a: Number,
  b: Number
});

// 创建Model
const Document = mongoose.model('Document', documentSchema);

// 连接到MongoDB数据库
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('Connected to MongoDB');

  // 查询文档
  const query = { a: { $gt: this.b + 1 } };

  // 注意:这里的`this`关键字在查询中不可用。你需要在实际查询时传递具体的值。
  Document.findOne(query, (err, doc) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log(doc);
  });

  // 更好的方法是直接使用具体的值
  const specificBValue = 3; // 假设b的值为3
  const specificQuery = { a: { $gt: specificBValue + 1 } };
  
  Document.findOne(specificQuery, (err, doc) => {
    if (err) {
      console.error(err);
      return;
    }
    console.log(doc); // 输出符合查询条件的文档
  });

}).catch((error) => {
  console.error('Failed to connect to MongoDB:', error);
});

解释

  • SchemaModel: 首先定义一个Mongoose Schema,并基于该Schema创建一个Model。
  • 连接数据库: 使用mongoose.connect连接到MongoDB数据库。
  • 查询文档: 在查询条件中直接使用具体的值(例如specificBValue),而不是尝试引用this关键字,因为this在查询上下文中不适用。

这种方法可以让你更灵活地构建查询条件,并且避免了直接引用未定义变量的问题。


我希望拿到key值在条件中做运算,谢谢。

有想法,不过很难实现,印象中每看过类似的api,找到可以通知我

貌似这种情况只能用where,摘自官网doc:

Use the $where operator to pass a string containing a JavaScript expression to the query system to provide greater flexibility with queries. Consider the following:

db.collection.find( { $where: "this.a == this.b" } );

$where evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).

In general, you should use $where only when you can’t express your query using another operator. If you must use $where, try to include at least one other standard query operator to filter the result set. Using $where alone requires a table scan.

看来真的只能$where了,多谢两位的关注和回答。

我想我还是在插入文档的时候,修改文档结构吧,先做出运算结果以方便今后的查询。

在MongoDB的查询中,如果你需要引用文档(记录)中的key值,可以使用聚合管道(Aggregation Pipeline)或者直接通过查询操作符来处理。对于你提供的示例,你可以使用聚合管道中的$expr操作符来引用文档内的字段。

假设你的集合名称为myCollection,并且你想找到a字段的值大于b字段值加1的所有文档,可以按以下方式编写查询:

示例代码

const MongoClient = require('mongodb').MongoClient;
const uri = "your_mongodb_connection_string_here";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function findDocuments() {
    try {
        await client.connect();
        const database = client.db('your_database_name');
        const collection = database.collection('myCollection');

        // 使用 $expr 操作符和 $gt 来引用文档内的字段
        const result = await collection.find({
            $expr: {
                $gt: ["$a", { $add: ["$b", 1] }]
            }
        }).toArray();

        console.log(result);
    } catch (error) {
        console.error("Error:", error);
    } finally {
        await client.close();
    }
}

findDocuments();

解释

  • collection.find() 方法用于执行查询。
  • $expr 允许你在查询中使用聚合表达式。
  • $gt 是一个比较操作符,表示“大于”。
  • "$a""$b" 是引用文档内部字段的方式。
  • { $add: ["$b", 1] } 表示将b字段的值加1。

这种方式允许你在查询条件中动态地引用文档内的字段值,而不需要在JavaScript层面进行预处理或额外的逻辑判断。

回到顶部