You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB Node驱动查询:筛选含指定字段且城市为芝加哥的文档

MongoDB Node驱动查询实现

需求说明

需要筛选出同时满足以下两个条件的文档:

  • city字段值为'Chicago'
  • 文档中存在cats_owned字段 或 dogs_owned字段

查询代码实现

使用MongoDB Node驱动的find方法,结合$and、$or和$exists操作符构建查询条件:

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

async function getTargetDocuments() {
  // 替换为你的MongoDB连接字符串
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

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

    // 构建查询条件
    const query = {
      $and: [
        { city: 'Chicago' },
        {
          $or: [
            { cats_owned: { $exists: true } },
            { dogs_owned: { $exists: true } }
          ]
        }
      ]
    };

    // 执行查询并转为数组返回
    const matchedDocs = await collection.find(query).toArray();
    console.log('符合条件的文档:', matchedDocs);
    return matchedDocs;
  } finally {
    // 关闭连接
    await client.close();
  }
}

// 调用查询函数
getTargetDocuments().catch(console.error);

逻辑说明

  • $and:保证city匹配和字段存在两个条件同时成立
  • $or:匹配存在cats_owned或dogs_owned任意一个字段的文档
  • $exists: true:指定字段必须存在于文档中

执行该查询后,会返回James和Leilani的文档,与预期结果一致。

内容的提问来源于stack exchange,提问作者stanley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:06:28