Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

mongodb - How match nested fields in mongo by using the match clause?

I am trying to match nested fields in a document in mongo but my query is not working.

Configuration:

[
  {
    linenumber: "car",
    type: "004",
    nested: {
      info: {
        subinfo: "B"
      }
    },
    
  },
  {
    linenumber: "car",
    type: "005",
    nested: {
      info: {
        subinfo: "G"
      }
    },
    
  }
]

query:

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          linenumber: "car"
        },
        {
          nested: {
            info: {
              subinfo: {
                $in: [
                  "B",
                  "G"
                ]
              }
            }
          }
        }
      ]
    }
  },
  {
    $group: {
      _id: null,
      types: {
        $addToSet: "$type"
      }
    }
  }
])

I am using the mongoplayground to test. Here is the link: https://mongoplayground.net/p/nND59iO1339

I am getting no documents found.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are almost there. You need to use dot notation.

play

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          linenumber: "car"
        },
        {
          "nested.info.subinfo": { //Dot notation
            $in: [
              "B",
              "G"
            ]
          }
        }
      ]
    }
  },
  {
    $group: {
      _id: null,
      types: {
        $addToSet: "$type"
      }
    }
  }
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...