MongoDB聚合查询:将数组字段转换为布尔值(依据指定值是否存在)
MongoDB Aggregation: Convert Array Field to Boolean Based on Presence of Specific Value
Absolutely! You can do this with MongoDB's aggregation framework without filtering out any documents—we'll just replace the tags array with a boolean flag based on whether it contains your target value. Here's the query you need:
db.yourCollection.aggregate([ { $addFields: { tags: { $in: ['tag that matters', '$tags'] } } } ])
Let's break down what's happening here:
$addFieldsstage: This lets us either add new fields or replace existing ones (which is exactly what we want fortags) while keeping all other document fields intact.$inoperator: This checks if the first value ('tag that matters') exists in the array specified by the second value ($tags, our original array field). It returnstrueif the value is found,falseotherwise—perfect for your use case.
Example Output:
For your sample document:
{ _id: ObjectId('604edf91571e7ab19cc2c238'), timestamp: 1616164767.773929, name: 'some name', metric1: 1, metric2: 2, metric3: 3, tags: ['tag1', 'tag2', 'tag3', 'tag that matters'] }
The result will be:
{ _id: ObjectId('604edf91571e7ab19cc2c238'), timestamp: 1616164767.773929, name: 'some name', metric1: 1, metric2: 2, metric3: 3, tags: true }
And for a document where tags doesn't contain 'tag that matters' (e.g., tags: ['tag1', 'tag2']), the tags field will be set to false instead—no documents are excluded from the results.
内容的提问来源于stack exchange,提问作者unltd_J
相关产品推荐
相关产品推荐

