mongodb查询问题?
黄舟
黄舟 2017-05-02 09:18:58
0
2
518

应该如何查询某一条记录中“ 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
}
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
迷茫

The most direct inquiry:

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

Then the returned object directly calls obj.comments.body

伊谢尔伦

The _id you query is of ObjectId type, so you also need to use ObjectId type data to query, not String type data;
If you are using mongoose, try this method, before querying, put your string Convert to ObjectId type

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

Full query:

db.collection.find({ "comments._id":mongoose.Types.ObjectId('56fb91c6c4b8801709aec38a') })
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template