$in operator is responsible to select
those records where the value of the fields is equal to any elements specified
in the array.
Same as $nin operator is responsible
to select those records where the value of the field is not equal to any elements
specified in the array.
Syntax:
{
field: { $in: [<value1>, <value2>, ... <valueN> ] } }
|
{
field: { $nin: [ <value1>, <value2> ... <valueN> ]} }
|
Example:
Suppose we have a
collection “order” and we have to select those records which quantity is 2, 4(we
will use here $in operator) same as if we want to select those records which
quantity is not equals to 2, 4 (we will use here $nin operator).
{
"_id" : 1, "item" : "item1", "qty" :
1, "Price" : 500 }
{
"_id" : 2, "item" : "item1", "qty" :
2, "Price" : 200 }
{
"_id" : 3, "item" : "item1", "qty" :
4, "Price" : 300 }
{
"_id" : 4, "item" : "item1", "qty" :
8, "Price" : 700 }
{
"_id" : 5, "item" : "item1", "qty" :
2, "Price" : 500 }
|
Query:
//for
$in
db.Order.find({qty:{$in:[2,4]}})
|
//for
$nin
db.Order.find({qty:{$nin:[2,4]}})
|
Results:
For $in
{
"_id" : 2, "item" : "item1", "qty" :
2, "Price" : 200 }
{
"_id" : 3, "item" : "item1", "qty" :
4, "Price" : 300 }
{
"_id" : 5, "item" : "item1", "qty" :
2, "Price" : 500 }
|
For $nin
{
"_id" : 1, "item" : "item1", "qty" :
1, "Price" : 500 }
{
"_id" : 4, "item" : "item1", "qty" :
8, "Price" : 700 }
|
No comments:
Post a Comment
Please do not enter any spam link in the comment box.