MongoDB find 查询 字段的值 在 数组中的所有文档 返回指定字段
时间: 2024-04-29 12:23:57 浏览: 10
可以使用 MongoDB 中的 $in 操作符来实现这个查询,同时使用投影操作符 $project 来指定返回的字段。具体语法如下:
```
db.collection.find({ field: { $in: [value1, value2, ...] } }, { field1: 1, field2: 1, ... })
```
其中,field 表示要查询的字段,value1、value2 等表示数组中的元素值,field1、field2 等表示要返回的字段。
例如,假设有一个名为 users 的集合,其中包含一个名为 hobbies 的数组字段,要查询出所有喜欢游泳的用户的姓名和年龄,可以使用以下命令:
```
db.users.find({ hobbies: { $in: ["swimming"] } }, { name: 1, age: 1, _id: 0 })
```
这个命令会返回所有 hobbies 数组中包含 "swimming" 的文档,并只返回这些文档中的 name 和 age 字段,不返回 _id 字段。
相关问题
node.js 中 MongoDB find 查询 字段的值 在 数组中的所有文档 返回指定字段
可以使用 MongoDB 的 $in 操作符来查询字段的值在一个数组中的所有文档,并返回指定字段。在 Node.js 中,可以使用官方的 MongoDB 驱动程序来实现这一操作。
下面是一个示例代码,假设有一个名为 "users" 的集合,其中包含一个名为 "tags" 的数组字段,需要查询所有 "tags" 中包含 "node.js" 的文档,并返回它们的 "name" 和 "email" 字段:
```javascript
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<database>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(async err => {
const collection = client.db("test").collection("users");
// 查询所有 "tags" 中包含 "node.js" 的文档,并返回它们的 "name" 和 "email" 字段
const result = await collection.find({ tags: { $in: ['node.js'] } }, { projection: { name: 1, email: 1, _id: 0 } }).toArray();
console.log(result);
client.close();
});
```
在上面的代码中,使用了 MongoDB 的 $in 操作符来查询 "tags" 中包含 "node.js" 的文档。使用 projection 参数来指定只返回 "name" 和 "email" 字段,而不返回默认的 "_id" 字段。最后使用 toArray() 方法将查询结果转换为数组并进行输出。
MongoDB find 查询 字段的值 在 数组中的所有文档
可以使用 $in 操作符来查询一个字段的值在指定数组中的所有文档,语法如下:
```
db.collection.find({ field: { $in: [ value1, value2, ... ] } })
```
其中,field 为需要查询的字段名,$in 表示在指定数组中查找,[ value1, value2, ... ] 为需要查找的值的数组。
示例:查询 score 字段的值在 [80, 90, 100] 中的所有文档,可以使用以下命令:
```
db.students.find({ score: { $in: [ 80, 90, 100 ] } })
```
该命令会返回 score 字段的值在 [80, 90, 100] 中的所有文档。