Aemon
Aemon

Reputation: 25

How to do such query in MongoDB

Here is an example of my documents.

  { username: 'John', score: 10 },
  { username: 'John', score: 9 },
  { username: 'John', score: 8 }, 
  { username: 'Alice', score: 9 }, 
  { username: 'Bob', score: 7 }

I want to select all the users whose score has never been 10.

Expected output:

  { username: 'Alice', score: 9 }, 
  { username: 'Bob', score: 7 }

Upvotes: 0

Views: 64

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

As per your comment in above answer, If your documents contains following documents :

{ "_id" : ObjectId("55713e614e3a37ae89ef7b4b"), "username" : "John", "score" : 10 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4c"), "username" : "John", "score" : 9 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4d"), "username" : "John", "score" : 8 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4e"), "username" : "Alice", "score" : 9 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4f"), "username" : "Bob", "score" : 7 }

and you want to display those user whose score never been 10 means in above conditions Alice and Bob data you required. So check this below query :

db.collectionName.find({"username":{"$nin":db.collectionName.distinct("username",{"score":10})}})

this db.collectionName.distinct("username",{"score":10})distinct return array of those user whose score:10 and use this array in find to check those username whose nin in distinct array.

Upvotes: 2

Related Questions