Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$ne
该$ne运算符用于匹配字段值不等于指定值的文档。它是一个比较运算符,可以在查询谓词中用于筛选文档。
Planner 版本 2.0 添加了对索引的支持$ne。
参数
-
field:要检查的字段。
-
value:要检查的值。
示例(MongoDB 外壳)
在此示例中,我们将查找users集合中该status字段不等于的所有文档"active"。
创建示例文档
db.users.insertMany([
{ name: "John", status: "active" },
{ name: "Jane", status: "inactive" },
{ name: "Bob", status: "suspended" },
{ name: "Alice", status: "active" }
]);
查询示例
db.users.find({ status: { $ne: "active" } });
输出
[
{
_id: ObjectId('...'),
name: 'Jane',
status: 'inactive'
},
{
_id: ObjectId('...'),
name: 'Bob',
status: 'suspended'
}
]
代码示例
要查看使用该$ne命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function main() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const users = db.collection('users');
const result = await users.find({ status: { $ne: 'active' } }).toArray();
console.log(result);
await client.close();
}
main();
- Python
-
from pymongo import MongoClient
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
users = db['users']
result = list(users.find({ 'status': { '$ne': 'active' } }))
print(result)
client.close()