I have the following schema:
{
"_id" : 27,
"n" : [{
"d" : new Date("Sat, 24 Dec 2011 17:03:00 GMT +04:00"),
"e" : ObjectId("4f0aef5346b3b88013000001"),
"f" : [26, 10, 16],
"k" : new Date("Mon, 09 Jan 2011 17:44:51 GMT +04:00"),
"t" : "f",
"u" : 10
}, {
"a" : ObjectId("4f0c208846b3b8140f000000"),
"d" : new Date("Tue, 10 Jan 2012 15:27:21 GMT +04:00"),
"p" : [ObjectId("4f0c209046b3b8340f000000"), ObjectId("4f0c209346b3b8340f000001"), ObjectId("4f0c209646b3b8340f000002"), ObjectId("4f0c209946b3b8340f000003")],
"t" : "p",
"u" : 10
}]
}
and this query removes all of the sub elements if at least one satisfy it
db.newsFeed.update({ "_id" : 27, },{
$pull : {
'n' : {
'd' : {
$lte : new Date(2012, 1, 1)
}
}
}
});
so the document becomes like this,
{
“_id” : 27,
“n” : []
}
what am I doing wrong, and more important what should I do to pull just some of the elements?
I think your query is fine, the problem is the date you’re using.
Instead of:
Try:
Try typing them in the shell by themselves and you’ll get back these results:
At least, that’s what I see in my shell. Using the “new” returns a date that matches on both elements of your array, so they’re both removed. Using ISODate directly creates the date object you’re looking for and only matches on the first result.
The Date constructor takes a zero based month, so you want this if you want to use new: