且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据数组中的条件从数组中获取不同的值

更新时间:2023-02-26 10:11:52

使用 .aggregate() 以及一些后期处理以仅获取数组响应中的值".

Query conditions with .distinct() apply to "document selection" and not the array entries contained "within" the document. If you need to "filter" array content then you apply .aggregate() instead, as well as a little post processing to get only the "values" in the array response.

db.collection.aggregate([
  { "$match": { "_id": "TEST" } },
  { "$unwind": "$payload" },
  { "$match": { "payload.status": { "$in": ["TRUE","FALSE"] } } },
  { "$group": { "_id": "$payload._id" } },
]).map( d => d._id );

其中的主要部分是 $ unwind > 流水线阶段,主要是因为您希望以后将数组中的值用作

The main parts there are the $unwind pipeline stage which you do primarily because you want the values from within the array to use later as the key to $group on. This essentially produces a new document for each array member, but each document only contains that array member. It's "denormalizing" for MongoDB structures that contain arrays.

下一件事是以下 $ match > 管道,它与任何查询一样工作,并且仅选择符合条件的文档.由于所有数组成员现在都是文档",因此不匹配的条目(作为文档)将被排除在外.您可以选择使用 $ filter 提取数组,但由于我们需要 $ unwind 在下一阶段,我们也可以简单地 $ match .

The next thing is the following $match pipeline, which works like any query and only selects documents that match the conditions. Since all array members are now "documents" then non matching entries ( as documents ) get excluded. You could alternately use $filter to extract whilst still an array, but since we need $unwind for the next stage we may as well simply $match.

这时,只剩下符合条件的数组条目. $ group 是为了获得不同"的值,因此通常您会选择更广泛的范围,而不仅仅是单个文档或此处的值尚未完全不同的任何内容.因此,这实际上只是保持 的所有相同行为.

At this point you are only left with the array entries that match the conditions. The $group is to obtain "distinct" values, so typically you would do this over a wider selection than just a single document or anything where the values here are not already distinct. So this is really just keeping all the same behavior of .distinct() intact.

最后,由于 .aggregate() .distinct() ,因为它在结果中返回文档",我们只需使用

Finally, since the output of .aggregate() differs from the design of .distinct() in that it returns "documents" in results, we simply use the .map() method to process the cursor results and return only the "values" from the specific document property as an "array".