Home>

How to implement a function similar to distinct in sql in mongodb, query all the values ​​of a certain field,Today we will discuss this issue.

The mongodb destinct command is to get a list of different values ​​in a particular field.This command applies to ordinary fields,Array fields and array embedded documents.

mongodb distinct statement:

db.users.distinct ("last_name")

Equivalent to the sql statement:

select distinct last_name from users

Represents the return of different recordsets based on the specified field.

A simple example:

//
>db.addresses.insert ({"zip-code":10010})
>db.addresses.insert ({"zip-code":10010})
>db.addresses.insert ({"zip-code":99701})
>// shell helper:
>db.addresses.distinct ("zip-code");
[10010, 99701]
>// running as a command manually:
>db.runcommand ({distinct:"addresses", key:"zip-code"})
{"values":[10010, 99701], "ok"
//
>db.comments.save ({"user":{"points":25}})
>db.comments.save ({"user":{"points":31}})
>db.comments.save ({"user":{"points":25}})
>db.comments.distinct ("user.points");
[25, 31]

That's all for this article.Hope everyone likes it.

  • Previous PHP Streams (stream) detailed introduction and use
  • Next Example usage of PHP stream_context_create () function