[英]MongoDB: Check if a field is same in all the documents in that collection
How could I check whether a specific field's value if same in all the document in that collection.我如何检查该集合中所有文档中特定字段的值是否相同。
I have a collection called Game
where I store the game responses of the users and in the game, the logic should check whether the responses are all equal or not, so how could I do it?我有一个名为
Game
的集合,我在其中存储用户的游戏响应,并且在游戏中,逻辑应该检查响应是否都相等,那么我该怎么做呢?
You need to do the opposite你需要做相反的事情
find({field: {$ne: expectedValue}})
If you get a response for this query, then there are documents which is not having the desired value.如果您收到此查询的响应,则说明存在不具有所需值的文档。
You can get the count of unique values of that field.您可以获得该字段的唯一值的计数。 If more than 1, they are not the same.
如果大于 1,则它们不一样。
You can also group by the field value.您还可以按字段值分组。 If more than 1 record, they are not the same.
如果超过 1 条记录,则它们不一样。
const rows = await myCollection.aggregate([
{
$group: {
_id: '$theField'
}
}
]).toArray()
if (rows.length === 1){
// same field value
}
Or do the counting in the pipeline to save bandwidth.或者在管道中进行计数以节省带宽。
const rows = await myCollection.aggregate([
{
$group: {
_id: '$theField'
}
},
{ $count: 'count' }
]).toArray()
if (rows.length && rows[0].count === 1) {
// same value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.