MongoDB检索特殊sports字段文档及单值转数组更新问题
Hey there! Let's tackle your two MongoDB questions one by one, with clear examples you can use right away.
1. 检索符合三种sports属性情况的文档
You need to target documents where sports is either an empty array, null, or doesn't exist at all. We can use the $or operator to combine these three conditions into a single query:
db.students.find({ $or: [ { sports: { $exists: false } }, // 匹配sports字段不存在的文档 { sports: null }, // 匹配sports为null的文档 { sports: { $size: 0 } } // 匹配sports为空数组的文档 ] })
小提示:
If you want to return only specific fields (instead of the full document), add a projection parameter at the end, like:
db.students.find( { /* 上述条件 */ }, { name: 1, _id: 0 } // 只返回name字段,不返回_id )
2. 将单值sports转为数组并添加新运动
For documents where sports is a single string (e.g., sports: "Badminton"), we'll use MongoDB's pipeline-based update (available in 4.2+) to convert the string to an array and append your new sport. Here's how:
示例:添加"Tennis"到单值sports字段
db.students.updateMany( { sports: { $type: "string" } }, // 匹配所有sports为字符串类型的文档 [ { $set: { sports: { $concatArrays: [ [ "$sports" ], // 将原字符串转为单元素数组 [ "Tennis" ] // 要添加的新运动(可以替换成你需要的内容) ] } } } ] )
解释:
{ $type: "string" }ensures we only target documents wheresportsis a single string value, not arrays or nulls.- The pipeline update lets us reference the existing
sportsvalue directly. We wrap it in[ "$sports" ]to turn it into an array, then use$concatArraysto merge it with the new sport array. - After running this, a document with
sports: "Badminton"will becomesports: [ "Badminton", "Tennis" ].
If you want to add multiple sports at once, just expand the second array: [ "Tennis", "Swimming" ].
内容的提问来源于stack exchange,提问作者Ernesto_Che

