简体   繁体   English

MongoDB:检查该集合中所有文档中的字段是否相同

[英]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.

相关问题 向 mongodb 集合中的所有文档添加字段 - add field to all documents in mongodb collection 查询在 MongoDb 集合中的所有文档中创建一个新字段 - Query to create a new field in all documents in MongoDb collection 向所有文档添加字段 MongoDB - Adding a field to all documents MongoDB MongoDB - 更新集合中的所有文档,使用文档中已存在的另一个字段的值添加新字段 - MongoDB - Update all documents in a collection, adding a new field using value from another field that is already present in the document 将一个新字段添加到集合的所有文档中,将文档字段中的值添加到 MongoDB (Mongoose) 中,记录为 300K+ - Add a new field to all documents of a collection with the value from the document field into MongoDB (Mongoose) with records of 300K+ MongoDB复制和更新同一集合中的多个文档 - MongoDB Copy and Update Multiple Documents in same collection 在集合的所有文档中添加字段 - MongoDB - Add fields in all documents of a collection - MongoDB 在 MongoDB 中的特定时间删除集合的所有文档 - Remove all documents of a collection at specific time in MongoDB MongoDB中许多具有相同字段或一个数组的文档 - Many documents with the same field or one array in MongoDB 所有文档中的mongoDB +节点更新字段 - mongoDB + Node update field from all documents
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM