【问题标题】:how to get the matching document inside a array in mongodb?如何在mongodb的数组中获取匹配的文档?
【发布时间】:2013-04-18 19:30:49
【问题描述】:

我的收藏是这样的

{
 _id :"",
 name:[
  {
   firstName:"",
   lastName:"",
  }
 ]
}

我需要在文档中找到匹配的名字。 如何在查询中实现这一点? 我是 mongodb 的新手。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:
    db.collection.find({name: {$elemMatch: {firstName: "Raj"}}});
    

    如需了解更多详情,请查看documentation for $elemMatch

    【讨论】:

    • @Raj koi nahi bhai。这是我的荣幸:)
    【解决方案2】:

    @Sushant Gupta 提供了正确的答案,但是我会说您也可以这样做,从而增加一点风味:

    db.collection.find({'name.firstName': 'Raj'}, {'name.$':1})
    

    收件人:matching firstName in the documents

    这背后的关键是 MongoDB 会将文档中的单个多键出现视为普通的平面字段,允许您像这样向下查询它们。

    您看到的第二个参数实际上是一个投影(http://docs.mongodb.org/manual/reference/projection/elemMatch/),它告诉 MongoDB 基本上从主文档中投影出匹配 name 子文档的 FIRST(如果需要更多,则需要使用聚合框架)。

    请注意,如果您像这样添加两个或多个多键字段:

    db.collection.find({'name.firstName': 'Raj', 'name.lastName': ''}, {'name.$':1})
    

    然后您将需要使用$elemMatch,但是,对于像这样的小型单字段查询,或者您有意在文档中的所有多键字段中搜索两个值,点表示法 (http://docs.mongodb.org/manual/reference/glossary/#term-dot-notation) 效果很好。

    【讨论】:

      【解决方案3】:

      这就是解决您问题的方法:

      db.MyCollection.find(  { name : { $elemMatch: { firstName : "valueGoesHere"} } } )
      

      【讨论】:

        猜你喜欢
        • 2019-09-03
        • 1970-01-01
        • 2018-10-23
        • 2020-10-16
        • 2018-07-14
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2018-10-08
        相关资源
        最近更新 更多