[SERVER-15245] findAndModify fail to addToSet a field, while querying by the same field. Created: 12/Sep/14  Updated: 12/Sep/14  Resolved: 12/Sep/14

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: 2.6.2
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Tamer Mohammed AbdulRadi Assignee: Unassigned
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates SERVER-3946 Update with $addToSet/$push with a qu... Closed
Operating System: ALL
Steps To Reproduce:

1. create a new empty collection "users"
2. Execute the following query, should fail

> db.users.findAndModify({query: {emails:"test@gmail.com"}, update:{"$addToSet": {"emails": "test@gmail.com"}, "$set": {"name": "Tamer"}}, upsert: true})
2014-09-12T22:25:15.414+0300 findAndModifyFailed failed: {
	"value" : null,
	"errmsg" : "exception: Cannot apply $addToSet to a non-array field. Field named 'emails' has a non-array type String in the document INVALID-MUTABLE-ELEMENT",
	"code" : 16836,
	"ok" : 0
} at src/mongo/shell/collection.js:614

3. Execute this query, should pass

> db.users.findAndModify({query: {emails: {$elemMatch: { $regex: 'test@gmail.com', $options: 'i' }}}, update:{"$addToSet": {"emails": "test@gmail.com"}, "$set": {"name": "Tamer"}}, upsert: true})
null
> db.users.find()
{ "_id" : ObjectId("541349cd912259e2bc9c311b"), "emails" : [ "test@gmail.com" ], "name" : "Tamer" }

Participants:

 Description   

Read Steps To Reproduce first.
I think findAndModify with upsert flag in case the object is not found, uses the query as the schema of the object. Query like:

{emails:"test@gmail.com"}

makes Mongodb thinks emails field contain string (although the collection is empty). While query like {$elemMatch: { $regex: 'test@gmail.com', $options: 'i' }} works just fine.

I tested only on v2.6.2

Note: Replacing $addToSet with $push, results in the same issues.



 Comments   
Comment by Scott Hernandez (Inactive) [ 12/Sep/14 ]

This behavior has already been record here: SERVER-3946

In 2.6 the error message has changed slightly.

Generated at Thu Feb 08 03:37:26 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.