gpt4 book ai didi

MongoDB:$elemMatch 和 $and 在数组中查找对象有什么区别?

转载 作者:行者123 更新时间:2023-12-04 16:01:08 28 4
gpt4 key购买 nike

查询运算符$and的用法有什么逻辑区别吗?

db.collection.find({$and: [{"array.field1": "someValue"}, {"array.field2": 3}]})

以及投影算子的用法 $elemMatch
db.collection.find({array: {$elemMatch: {field1: "someValue", field2: 3}}})

查找包含数组内的对象字段的文档?

最佳答案

我将用一个例子来解释这一点。考虑收藏 arrays .它有一个名为 arr 的字段这是一个嵌入文档的数组(具有字段 ab )。
arrays中的一些文档收藏:

{ "_id" : 1, "arr" : [ { "a" : "a1", "b" : "b1" }, { "a" : "a2", "b" : "b2" } ] }
{ "_id" : 2, "arr" : [ { "a" : "a1", "b" : "b11" }, { "a" : "a2", "b" : "b22" } ] }
{ "_id" : 3, "arr" : [ { "a" : "a2", "b" : "b1" }, { "a" : "a", "b" : "b1" } ] }
{ "_id" : 4, "arr" : [ { "a" : "a1", "b" : "b91" }, { "a" : "a29", "b" : "b1" } ] }

我想找到所有带有数组嵌入文档字段的文档 a="a1"b="b1" .请注意,这必须在数组的同一元素内嵌文档中。我用 $elemMatch 为此并获得所需的结果。
> db.arrays.find( { arr: { $elemMatch: { a: "a1", b: "b1" } } } )
==>
{ "_id" : 1, "arr" : [ { "a" : "a1", "b" : "b1" }, { "a" : "a2", "b" : "b2" } ] }

现在,如果我使用 $和像以下查询中的运算符,结果不正确。如您所见,选择了一个附加文档。该查询使用数组嵌入文档字段 a="a1"b="b1" .
> db.arrays.find({$and: [ { "arr.a": "a1" }, { "arr.b": "b1" } ] } )
==>
{ "_id" : 1, "arr" : [ { "a" : "a1", "b" : "b1" }, { "a" : "a2", "b" : "b2" } ] }
{ "_id" : 4, "arr" : [ { "a" : "a1", "b" : "b91" }, { "a" : "a29", "b" : "b1" } ] }

因此,使用 $and运算符不用于此目的(即,查询子文档数组的多个字段)。

此外,要查询数组嵌入文档字段( 只有一个字段 ) $elemMatch不是必需的,例如:
> db.arrays.find( { "arr.a": "a2" } )
==>
{ "_id" : 1, "arr" : [ { "a" : "a1", "b" : "b1" }, { "a" : "a2", "b" : "b2" } ] }
{ "_id" : 2, "arr" : [ { "a" : "a1", "b" : "b11" }, { "a" : "a2", "b" : "b22" } ] }
{ "_id" : 3, "arr" : [ { "a" : "a2", "b" : "b1" }, { "a" : "a", "b" : "b1" } ] }

关于MongoDB:$elemMatch 和 $and 在数组中查找对象有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58384199/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com