• Type: Icon: New Feature New Feature
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 1.9.1
    • Affects Version/s: None
    • Component/s: Querying
    • None

      In addition to the $or operator (http://jira.mongodb.org/browse/SERVER-205), I feel there is a need for a $and operator.
      A possible way to write it could be:

      $and: [

      { <condition1> }

      ,

      { <condition2> }

      ]

      Why it is needed:
      Condition blocks are physically objects. Thus, we cannot have the same property used twice, preventing the use of the same construct/property multiple times in a query.

      Example:
      Suppose I have a collection of user sessions.
      Each session can contain an arbitrary list of key-value pairs, possibly repeated (ie. an identical key can be listed several times in different objects of the list). Additionally, each key value pair has a timestamp, for history purpose.

      A document sample would be
      {
      session_id: 1,
      data: [

      { name: 'johm', timestamp: 20100504120000 }

      ,

      { lastname: 'doe', timestamp: 20100505120000 }

      ,

      { name: 'john', #the user corrected the initial input timestamp: 20100504120100 }

      ]
      }

      Now, when I want to query for a session with an user named john, I would need to use $elemMatch, since I can't match the full element because of the variable timestamp, like below:

      find({
      data: {$elemMatch: {name: 'john'}}
      });

      Now, I want to look for john doe. But since I can't repeat the same $elemMatch key in the data condition object, I am stuck.
      The query below would run, but ignore the first condition, since it is being overwritten by the second.

      find({
      data: {
      $elemMatch:

      {name: 'john'}

      ,
      $elemMatch:

      {lastname: 'doe'}

      }
      });

      Possible solution with $and operator:

      find({
      data: {
      $and: [
      {$elemMatch: {name: 'john'}},
      {$elemMatch: {lastname: 'doe'}}
      ]
      }
      });

            Votes:
            59 Vote for this issue
            Watchers:
            41 Start watching this issue

              Created:
              Updated:
              Resolved: