MongoDB - 在数组上查询

2025-09-09 00:00    #MongoDB   #Querying  

查询数组 - MongoDB 手册 v8.0

$ne操作在数组的查询与我想的不一样

如果你希望能够匹配数组中有部分元素与 “red” 不匹配的文档,可以使用 $elemMatch 来精确匹配数组中的单个元素:

1db.newdb.find({
2  tags: { $elemMatch: { $ne: "red" } }
3})

查询数组元素

多个条件

1const cursor = db.collection('inventory').find({
2  dim_cm: { $gt: 15, $lt: 20 }
3});

数学描述

xA(x>=15)xA(x<=20) \exists x \in A( x>=15) \land \exists x \in A (x <=20)
1const cursor = db.collection('inventory').find({
2  dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
3});
xA(x>=15x<=20) \exists x \in A( x>=15 \land x <=20)
1const cursor = db.collection('inventory').find({
2  dim_cm: {$eq:20}
3});
xA(x=20) \exists x \in A( x=20)
1const cursor = db.collection('inventory').find({
2  dim_cm: {$ne:20}
3});

!!!注意这个查询是上面的查询的反面

¬xA(x=20)¬(x=20)(x!=20) \begin{matrix} \neg \exists x \in A(x = 20) \\ \forall \neg (x = 20) \\ \forall (x != 20) \end{matrix}