Querying multiple elements of an array with $elemMatch?

4,174 views
Skip to first unread message

Francisco J. Martin

unread,
Apr 18, 2011, 4:59:09 PM4/18/11
to mongod...@googlegroups.com
Hi there,

It looks like querying using $elemMatch returns the wrong number of documents when querying multiple elements of an array. See the 4th query below. Is this a bug or querying lists requires to follow the order of the elements in the list to get the right result?  In any case, it looks weird to get the same result in queries 3rd and 4th below.  Please let me know if I'm interpreting something in the wrong way. 

> db.jobs.count()
1
> db.jobs.findOne()
{
"_id" : ObjectId("4dac9dc203ce893305000000"),
"status" : 0,
"updated" : ISODate("2011-04-18T20:23:30.913Z"),
"tasks" : [
{
"status" : 2,
"name" : "upload"
},
{
"status" : 2,
"name" : "copy"
}
],
"created" : ISODate("2011-04-18T20:23:30.913Z"),
"board" : {
}
}

> db.jobs.find({'status': 0, 'tasks': {$elemMatch: {'name': 'upload', 'status': 2}}, 'tasks': {$elemMatch: {'name': 'copy', 'status': 2}}}).count()
1
[ok]

> db.jobs.find({'status': 0, 'tasks': {$elemMatch: {'name': 'upload', 'status': 2}}, 'tasks': {$elemMatch: {'name': 'copy', 'status': 1}}}).count()
0
[ok]

> db.jobs.find({'status': 0, 'tasks': {$elemMatch: {'name': 'copy', 'status': 2}}, 'tasks': {$elemMatch: {'name': 'upload', 'status': 2}}}).count()
1
[ok]

> db.jobs.find({'status': 0, 'tasks': {$elemMatch: {'name': 'copy', 'status': 1}}, 'tasks': {$elemMatch: {'name': 'upload', 'status': 2}}}).count()
1
[wrong]

 thanks in advance, francisco


Scott Hernandez

unread,
Apr 18, 2011, 5:38:04 PM4/18/11
to mongod...@googlegroups.com
You can't repeat the tasks field name like that. It will result in
just one field named "tasks" in the final doc.

You can try to use $all; I don't remember if it support $elemMatch
nesting like that.

You really want $and support which is coming very soon.

> --
> You received this message because you are subscribed to the Google Groups
> "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com.
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/mongodb-user?hl=en.
>

Francisco J Martin

unread,
Apr 18, 2011, 5:41:35 PM4/18/11
to mongodb-user
Hi again,

It looks like using $all is the right approach as previously posted in
the group. Thanks anyway.

> db.jobs.find({'status': 0,
... 'tasks': {
... $all: [
... {'$elemMatch': {'name': 'copy', 'status':
1}},
... {'$elemMatch': {'name': 'upload', 'status':
2}}]
... }
... }).count()
0
Reply all
Reply to author
Forward
0 new messages