简体   繁体   English

MongoDb 在子字段中查找字符串

[英]MongoDb find a string inside a subfield

Let's say we have a collection that has elements that look like this:假设我们有一个包含如下元素的集合:

{
"_id" : ObjectId(...),
"field1": "some_text",
"field2": {
                "subfield1" : [
                        "some_text",
                        "some_text",
                        "some_text"
                ],
                "subfield2" : [
                        "some_text",
                        "some_text"
                ],
                "subfield3" : [
                        "some_text"
                ]
        }
}

Now what I want to do is, I want to find all the ids that have a certain string inside the field2 value.现在我想要做的是,我想找到在 field2 值中具有某个字符串的所有 id。 Doesn't matter in which subfield.在哪个子领域无关紧要。 If there is such string there, I want that whole element to be returned.如果那里有这样的字符串,我希望返回整个元素。 Imagine that there are 100 subfields.假设有 100 个子字段。 I don't want to check each of them separately.我不想分别检查它们中的每一个。

How would this be done?这将如何完成?

Use this to put all values into one single array.使用它可以将所有值放入一个数组中。 Then it is easy to find a particular string in subfields array.然后很容易在subfields数组中找到特定的字符串。

db.collection.aggregate([
  {
    $set: {
      subfields: { $objectToArray: [ "$field2" ] }
    }
  },
  {
    $set: {
      subfields: {
        $reduce: {
          input: { $concatArrays: [ "$subfields.v" ] },
          initialValue: [],
          in: { $concatArrays: [ "$$value", "$$this" ] }
        }
      }
    }
  },
  {$match: {subfields: "whatever you are looking for"}},
  {$unset: "subfields"}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM