1
我想有一個返回一個布爾值,如果一個字段包含在數組中,喜歡的一步:
$project: {
// would return whether the field 'type' is banana or apple
isFruit: { $type: { $in: ['apple', 'banana'] } },
},
但是,這是行不通的。看看doc,我看不到包含測試。那可能嗎?
我想有一個返回一個布爾值,如果一個字段包含在數組中,喜歡的一步:
$project: {
// would return whether the field 'type' is banana or apple
isFruit: { $type: { $in: ['apple', 'banana'] } },
},
但是,這是行不通的。看看doc,我看不到包含測試。那可能嗎?
這有點令人費解,但你可以通過使用$filter
來過濾輸入數組做到這一點,只是元素匹配type
,然後比較反對[]
結果(如果有的話):
db.test.aggregate([
{$project: {
isFruit: { $ne: [[], { $filter: {
input: ['apple', 'banana'],
as: 'fruit',
cond: { $eq: ['$$fruit', '$type'] }
}}]}
}}
])
注意在MongoDB 3.2中添加了$filter
。
這看起來不錯!任何關於可能的性能缺點的想法? – Guig
@Guig我不確定它會如何擴展,您必須在真實場景中進行測試。 – JohnnyHK