在多维数组中,搜索MongoDB中特定位置的值。

huangapple go评论53阅读模式
英文:

MongoDB search in multi dimensional arrays for value in specific position

问题

给定这个 MongoDB 的三个对象:

{
    "_id" : 1,
    "array" : [
        [ "a1", "b1" ],
        [ "a2", "b2" ]
    ]
},
{
    "_id" : 2,
    "array" : [
        [ "a1", "b2" ],
        [ "a2", "b1" ]
    ]
},
{
    "_id" : 3,
    "array" : [
        [ "b1", "a1" ],
        [ "b2", "a2" ]
    ]
}

如何查找所有具有一个或多个嵌套数组中位置 1 的值为 "b1" 的文档?

例如:

如果我在嵌套数组的位置 1 搜索 "b1",我期望获取文档 1 和 2,但不包括 3。

如果我在嵌套数组的位置 0 搜索 "b1",我期望获取文档 3,但不包括 1 或 2。

我希望有一种类似通配符的方式,像 "array.*.1":"b1"。

英文:

Given this, three MongoDB objects

{
    "_id" : 1,
	"array" : [
		[ "a1", "b1" ],
		[ "a2", "b2" ]
	]
},
{
    "_id" : 2,
	"array" : [
		[ "a1", "b2" ],
		[ "a2", "b1" ]
	]
},
{
    "_id" : 3,
	"array" : [
		[ "b1", "a1" ],
		[ "b2", "a2" ]
	]
}

How to find the all Documents that have the value "b1" in array in position 1 of one or more nested arrays?

As example:

If I search for "b1" in position 1 of the nested arrays, I expect to get document 1 and 2 but not 3.

If I search for "b1" in position 0 of the nested arrays, I expect to get document 3 and not 1 or 2.

I was hoping for some kind of wildcard like "array.*.1":"b1"

答案1

得分: 1

如@rickhg12hs所示,解决方案在于使用$elemMatch(https://www.mongodb.com/docs/v6.0/reference/operator/query/elemMatch/)。

这允许您指定数组项内字段的所需内容(按名称或索引)。

如果该项是JSON对象,您可以指定字段名称以包含特定值,如果是数组,只需指定索引。

在我的情况下,解决方案是:

db.collection.find({
  "array": {
    "$elemMatch": {
      "0": "b1"
    }
  }
})

其中“0”是嵌套数组内的索引,而“b1”是所需的值。

如果是嵌套的JSON对象,只需将“0”替换为所需的字段名称。
有趣的是,如果字段名称恰好是“0”,那么您可以混合数组和对象并获得两者的结果。

英文:

As shown by @rickhg12hs, the solution lies in the usage of $elemMatch (https://www.mongodb.com/docs/v6.0/reference/operator/query/elemMatch/).

This allows you to specify the desired contents of a field (by name OR by index) inside the items of an array.

If the item is a json Object you can specify the field name to contain a specific value and if it's an array you can simply specify the index.

In my case, the solution is:

db.collection.find({
  "array": {
	"$elemMatch": {
	  "0": "b1"
	}
  }
})

With "0" being the index inside the nested array and "b1" the desired value.

I case of nested JSON Object, simply replace "0" by the desired field name.
Fun fact. If the field name happens to be "0" than you can mix arrays and objects and get results for both.

huangapple
  • 本文由 发表于 2023年6月19日 01:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76501724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定