您如何使用聚合框架仅 select MongoDB 具有子字段的文档?

How do you only select MongoDB documents that have a sub-field, using the aggregation framework?

如何在使用聚合时从 mongo 集合中过滤掉没有子字段的文档?

集合看起来像这样:

{ 
  "_id": ObjectId("adasdasd"),
  "obj": { "a": 1 }
},

{ 
  "_id": ObjectId("ergergerg"),
  "obj": { "b": 2 }
},

{ 
  "_id": ObjectId("adasdasd"),
  "obj": { "a": 3, "b": 4 }
},

如何将 aggregate() 函数仅用于 select 文档,其中 "obj" 字段包含 "b" 子字段?结果应如下所示:

{ 
  "_id": ObjectId("ergergerg"),
  "obj": { "b": 2 }
},

{ 
  "_id": ObjectId("adasdasd"),
  "obj": { "a": 3, "b": 4 }
},

我意识到我可以使用 find() 和 $exists,但我正在寻找使用 aggregate() 的解决方案。任何帮助是极大的赞赏。

超出我的想象:

$match: {'obj.b': { $exists: true, $ne: null } }

看看$match stage:

Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

The $match stage has the following prototype form:

{ $match: { } }

$exists operator:

$exists Syntax: { field: { $exists: } }

When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.

相关问题:How do you query for "is not null" in Mongo?