Given the following data structure:
{
"_id" : ObjectId("55760212e4b011ee8c72fb1f"),
"firstname" : "joe",
"lastname" : "blow",
"email" : "[email protected]",
"sysadmin" : false,
"siteadmin" : false,
"sites" : [
{
"siteId" : ObjectId("55760212e4b011ee8c72fb1e"),
"notification" : false
}
]
}
I'm trying to $pull
a nested sites
object using an ObjectId
as search criteria. The following code:
val siteSearch = MongoDBObject("siteId" -> siteId)
val query = MongoDBObject("sites" -> siteSearch)
db(collection).update(query, $pull(query))
generates for following query
{ "sites" : { "siteId" : { "$oid" : "55760212e4b011ee8c72fb1e"}}}
It's not removing the site, I'm assuming because I want the query
to look like:
{ "sites" : { "siteId" : ObjectId("55760212e4b011ee8c72fb1e")}}
I'm not sure how to make Cashbah issue the correct query.
First,
{ "$oid" : "55760212e4b011ee8c72fb1e"}
is the JSON representation of the BSON 12 bytes ObjectId type. Basically, the same thing asObjectId("55760212e4b011ee8c72fb1e")
. See http://docs.mongodb.org/manual/reference/mongodb-extended-json/#oidThen, as you match against an array item, you need to use
$elemMatch
in your query. But, as$pull
applies its query to each element as though it were a top-level object, you don't need it in the update expression.I don't have Casbah at hand right no, but using the Casbah DSL, you might use that alternate syntax I think:
From a Mongo shell perspective, this should be the same as: