如何访问mongodb数组中字典?

bnlyeluc  于 2023-04-20  发布在  Go
关注(0)|答案(1)|浏览(97)
{
    '_id': ObjectId('6433bc6cb47d316b01e0c3b6'),
    'name': {
        'coordinates_and_text': [
            [{
                    'BL': 3,
                    'BR': 4,
                    'TL': 1,
                    'TR': 2,
                    'text': 'abc'
                },
                {
                    'BL': 30,
                    'BR': 40,
                    'TL': 10,
                    'TR': 20,
                    'text': 'limited'
                }
            ],
            [{
                'BL': 300,
                'BR': 400,
                'TL': 100,
                'TR': 200,
                'text': 'hello'
            }]
        ]
    }
}

我试图访问“text”:“limited”在数组的数组。
我在命令行下面试过了,但它什么也没返回。

db.collection.find({'name.coordinates_and_text.text':'hello'})
mjqavswn

mjqavswn1#

选项1:使用$elemMatch

db.collection.find({
"name.coordinates_and_text": {
  "$elemMatch": {
   "$elemMatch": {
    "text": "hello"
    }
   }
  }
})

Playground

选项2您可以创建wildcard text index

mongos> db.x.createIndex( { '$**' : "text" },{ default_language: "none" , language_override : "none"} )
{
"raw" : {
    "clsuter/127.0.0.1:2017,127.0.0.1:2018,127.0.0.1:2019" : {
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
    }
},
"ok" : 1,
"operationTime" : Timestamp(1681129805, 4),
"$clusterTime" : {
    "clusterTime" : Timestamp(1681129805, 4),
    "signature" : {
        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
        "keyId" : NumberLong(0)
    }
}
}
mongos> db.x.aggregate([{$match : { $text: { "$search": "hello" } }}])
{ "_id" : ObjectId("6433bc6cb47d316b01e0c3b6"), "name" : { "coordinates_and_text" : [ [ { "BL" : 3, "BR" : 4, "TL" : 1, "TR" : 2, "text" : "abc" }, { "BL" : 30, "BR" : 40, "TL" : 10, "TR" : 20, "text" : "limited" } ], [ { "BL" : 300, "BR" : 400, "TL" : 100, "TR" : 200, "text" : "hello" } ] ] } }
mongos>

选项3您可以更改(here_is_how)schema,例如将key添加到第二个嵌套数组中,这样会更容易:

db.y.find({ "name.coordinates_and_text.t.text":"hello" })

(在示例中,第二个数组键是“t”):example

相关问题