$ne

On this page本页内容

Definition定义

$ne

Syntax: 语法:{ field: { $ne: value } }

$ne selects the documents where the value of the field is not equal to the specified value. 选择field值不等于指定value的文档。This includes documents that do not contain the field.这包括不包含该field的文档。

For comparison of different BSON type values, see the specified BSON comparison order.有关不同BSON类型值的比较,请参阅指定的BSON比较顺序

Examples示例

The following examples use the inventory collection. 以下示例使用inventory集合。Create the collection:创建集合:

db.inventory.insertMany( [
   {
      "item": "nuts", "quantity": 30,
      "carrier": { "name": "Shipit", "fee": 3 }
   },
   {
      "item": "bolts", "quantity": 50,
      "carrier": { "name": "Shipit", "fee": 4 }
   },
   {
      "item": "washers", "quantity": 10,
      "carrier": { "name": "Shipit", "fee": 1 }
   }
] )

Match Document Fields匹配文档字段

Select all documents in the inventory collection where quantity is not equal to 20:选择inventory集合中quantity不等于20的所有文档:

db.inventory.find( { quantity: { $ne: 20 } } )

The query will also select documents that do not have the quantity field.查询还将选择没有quantity字段的文档。

Example output:示例输出:

{
  _id: ObjectId("61ba667dfe687fce2f042420"),
  item: 'nuts',
  quantity: 30,
  carrier: { name: 'Shipit', fee: 3 }
},
{
  _id: ObjectId("61ba667dfe687fce2f042421"),
  item: 'bolts',
  quantity: 50,
  carrier: { name: 'Shipit', fee: 4 }
},
{
  _id: ObjectId("61ba667dfe687fce2f042422"),
  item: 'washers',
  quantity: 10,
  carrier: { name: 'Shipit', fee: 1 }
}

Perform an Update Based on Embedded Document Fields基于嵌入式文档字段执行更新

The following example sets the price field based on a $ne comparison against a field in an embedded document.以下示例基于$ne与嵌入文档中的字段进行比较来设置price字段。

db.inventory.updateMany( { "carrier.fee": { $ne: 1 } }, { $set: { "price": 9.99 } } )

Example output:示例输出:

{
  _id: ObjectId("61ba66e2fe687fce2f042423"),
  item: 'nuts',
  quantity: 30,
  carrier: { name: 'Shipit', fee: 3 },
  price: 9.99
},
{
  _id: ObjectId("61ba66e2fe687fce2f042424"),
  item: 'bolts',
  quantity: 50,
  carrier: { name: 'Shipit', fee: 4 },
  price: 9.99
},
{
  _id: ObjectId("61ba66e2fe687fce2f042425"),
  item: 'washers',
  quantity: 10,
  carrier: { name: 'Shipit', fee: 1 }
}

This updateMany() operation searches for an embedded document, carrier, with a subfield named fee. updateMany()操作搜索嵌入的文档carrier,其子字段名为feeIt sets { price: 9.99 } in each document where fee has a value that does not equal 1 or where the fee subfield does not exist.它在每个fee值不等于1或fee子字段不存在的文档中设置{ price: 9.99 }

The inequality operator $ne is not very selective since it often matches a large portion of the index. 不等式运算符$ne不是很有选择性,因为它通常匹配索引的很大一部分。As a result, in many cases, a $ne query with an index may perform no better than a $ne query that must scan all documents in a collection. 因此,在许多情况下,带有索引的$ne查询的性能可能并不比必须扫描集合中所有文档的$ne搜索好。See also Query Selectivity.另请参见查询选择性

Tip提示
See also: 参阅:
←  $lte$nin →