搜索

首页  >  问答  >  正文

mongodb查询问题?

应该如何查询某一条记录中“ comments”中的某条呢?为什么通过“_id”查询不到呢?

{
  "_id": "56fa1c5acb169bd213e485de",
  "title": "ReactJS学习笔记",
  "classify": "js",
  "desc": "React是一个JavaScript库文件",
  "author": "root",
  "body": "",
  "hidden": false,
  "meta": {
    "votes": 0,
    "favs": 0
  },
  "date": "2016-03-30T08:20:36.866Z",
  "comments": [
    {
      "body": "aaaa",
      "date": "2016-03-30T08:43:50.401Z",
      "guest": "A",
      "email": "xxxxxx@qq.com",
      "browser": "chrome",
      "_id": "56fb91c6c4b8801709aec38a"
    },
    {
      "_id": "56fb93ddc4b8801709aec38b",
      "browser": "chrome",
      "email": "xxxxxx@icloud.com",
      "guest": "tester",
      "date": "2016-03-30T08:52:45.445Z",
      "body": "bbbbb"
    }
  ],
  "__v": 0
}
黄舟黄舟2770 天前511

全部回复(2)我来回复

  • 迷茫

    迷茫2017-05-02 09:20:58

    最直接的查询:

    db.collection.find(
       {
          _id:ObjectId("56fa1c5acb169bd213e485de")
       }
    )

    然后返回的对象里面直接调用了 obj.comments.body

    回复
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-02 09:20:58

    你查询的_id是ObjectId类型,所以你也要用ObjectId类型的数据去查询,而不是String类型的数据;
    如果你用的是mongoose,试试这个方法,在查询前,把你的string转成ObjectId类型

    var mongoose = require('mongoose');
    mongoose.Types.ObjectId('56fb91c6c4b8801709aec38a');

    完整的查询:

    db.collection.find({ "comments._id":mongoose.Types.ObjectId('56fb91c6c4b8801709aec38a') })

    回复
    0
  • 取消回复