Mongodb
連接操作後根據值過濾 - MongoDB
我有以下格式的兩個集合 -
收藏1:
{ "_id": "col1id1", "name": "col1doc1", "properties": [ "<_id1>", "<_id2>", "<_id3>"] }
集合2:
{ "_id": "<_id1>", "name": "doc1", "boolean_field": false }, { "_id": "<_id2>", "name": "doc2", "boolean_field": true }, { "_id": "<_id3>", "name": "doc3", "boolean_field" : false }
所需的輸出是:
{ "_id": "col1id1", "name": "col1doc1", "property_names": ["doc1", "doc3"] }
collection1 中的 document欄位
properties
具有 collection2 中的三個文件 ID,但連接操作後的輸出應僅包含boolean_field
值為 as的那些false
。如何在 MongoDB 中使用連接操作執行此過濾器?
在 MongoDB 3.6+ 中,您可以將 a 添加
pipeline
到您的$lookup
階段以包含其他連接條件。由於您的源查找欄位是一個數組,因此解決方案沒有我預期的那麼明顯,但以下應該返回預期的結果:
db.collection1.aggregate([ { $match: { _id: "col1id1" }}, // Filtered lookup based on agg pipeline { $lookup: { from: "collection2", // let references fields in the original collection let: { property: "$properties" }, pipeline: [ { $match: // use $expr to compare fields using let variables { $expr: { $and: [ { $in: [ "$_id", "$$property" ] }, { $eq: [ "$boolean_field", false ] } ]} } }, { $project: { "_id": 0, "name": 1 }} ], as: "property_names" }}, // Project desired output fields { $project: { "name" : "$name", "property_names": { $map: { input: "$property_names", in: "$$this.name" } } } } ]).pretty()
樣本輸出:
{ "_id" : "col1id1", "name" : "col1doc1", "property_names" : [ "doc1", "doc3" ] }