用MongoDB子元素查询?

您可以为此使用位置运算符$。首先让我们创建一个包含文档的集合-

> db.subElementQueryingDemo.insertOne(
...    {
...       "ClientName":"Chris",
...       "Status": [ { "isMarried": true }, { "isMarried": false } ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf28c9dceb9a92e6aa1953")
}

以下是在find()方法的帮助下显示集合中所有文档的查询-

> db.subElementQueryingDemo.find().pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5ccf28c9dceb9a92e6aa1953"),
   "ClientName" : "Chris",
   "Status" : [
      {
         "isMarried" : true
      },
      {
         "isMarried" : false
      }
   ]
}

这是在MongoDB中查询子元素的方法-

> db.subElementQueryingDemo.find({ "Status.isMarried": true }, {ClientName: 1, 'Status.$': 1}).pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5ccf28c9dceb9a92e6aa1953"),
   "ClientName" : "Chris",
   "Status" : [
      {
         "isMarried" : true
      }
   ]
}