Home > Blockchain >  MongoDB: Check if a field is same in all the documents in that collection
MongoDB: Check if a field is same in all the documents in that collection

Time:02-05

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 ?

CodePudding user response:

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.

CodePudding user response:

You can get the count of unique values of that field. If more than 1, they are not the same.

You can also group by the field value. If more than 1 record, they are not the same.

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
}
  •  Tags:  
  • Related