0

I have such MongoDB Collection:

{
  date: date,
  domain: domain,
  visitors:  [ {owner:owner, ip:ip, views:views} ]
}

Now I want to check where date equals date AND domain equals domain it should delete the whole visitors array, e.g.:

collection.update({"date":date, {"domain":domain} {"$pull":{"visitors"}} )

How to make this work?

2 Answers 2

2

You could try use the $set operator to empty the visitors array instead of removing all items by using the $pull operator, which would be much faster as the $pull will have to do calculations on arrays:

db.collection.update( {"date": date, "domain": domain}, { $set : {"visitors": [] }} , {multi: true} )

The equivalent $pull operation would be

db.collection.update( {"date": date, "domain": domain}, { $pull : { "visitors": {} }}, {multi: true} )
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for added explanation.
@SirBenBenji No worries, glad you found it useful.
your $pull : { "visitors": {} } does not work for me.
1
db.test.update({"$and": [{date:"date"}, {domain:"domain"}]}, {"$set":{visitors:[]}})

You should use the $and operator to match your update query.

Removing all Elements from the Array is the same as setting the value of visitors to the empty array [ ]. But setting it to the empty array is quicker and easier to write and understand, so you should use this.

3 Comments

The $and isn't needed here as multiple query terms are implicitly ANDed already. Just use {date: date, domain: domain}.
yes, but his matching was also wrong and I think it is good to use an $and in the first place if you change your query later it is easier to update and understand.
I have encountered cases where the unnecessary use of $and has prevented the query optimizer from using the "right" index, so I've learned to only use it when actually needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.