mongodb 数组查询
发布于 8 年前 作者 youthfighter 4528 次浏览 来自 问答

这是我mongodb中存储的数据

{  
  "_id" : ObjectId("4ec0b2a4ecb31ca1968000fd"),  
  "id" : 1001,  
  "singer" : "刘德华",  
  "someReview" : [{  
      "user" : "dong",  
      "text" : "不好听"  
    }, {  
      "user" : "wan",  
      "text" : "打酱油"  
    }, {  
      "user" : "wan",  
      "text" : "真的挺不错,一直很喜欢刘德华"  
    }]  
}

我想通过查询得到

{  
  "_id" : ObjectId("4ec0b2a4ecb31ca1968000fd"),  
  "id" : 1001,  
  "singer" : "刘德华",  
  "someReview" : [{  
      "user" : "dong",  
      "text" : "不好听"  
    }]  
} 

应该怎么写查询语句?也就是说我想查询user为“dong”条目,而不是全部的数组信息。

7 回复
model.find({"someReview.user":"dong"},cb)

好像不管你怎么查询,都是这个整条数据吧,someReview 这是一个数组 ,我也是新手

model.aggregate([
  {
    $match: {
      id: 1001
    }
  }, {
    $unwind: 'someReview'
  }, {
    $project: {
      id: 1,
      singer: 1,
      user: '$someReview.user',
      text: '$someReview.text'
    }
  }, {
    $match: {
      user: 'dong'
    }
  }
]).toArray()
db.getCollection('position').aggregate([
  {
    $match: {
      id: '1001'
    }
  }, {
    $project: {
      id: 1,
      singer: 1,
      someReview: {
        $filter: {
          input: '$someReview',
          as: 'item',
          cond: {
            $eq: [
              "$$item.user", dong
            ]
          }
        }
      }
    }
  }
])

@webbought 不知道不试过没有,我查出来的是整条数据。而且确实应该是整条数据,因为数组满足条件,所以返回这一整条数据。

@falost 是的,正是因为这样,才求高手帮忙。

可以用下面的方法实现:

    db.getCollection('star').aggregate(
     {$match: {'id':1001}},
     {$unwind:'$someReview'},
     {$match:{'someReview.user':'dong'}}
    )
不过结果中的someReview字段是以json对象形式存在:
     {
     "_id" : ObjectId("57ee53805fe803887df7c97f"),
     "id" : 1001.0,
     "singer" : "刘德华",
     "someReview" : {
         "user" : "dong",
         "text" : "不好听"
     }
    } 
可以参考:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#pipe._S_unwind
回到顶部