How to emulate a subquery and remove value from an array

I’m attempting to remove the stringified ID from a document in one collection from an any arrays in another collection in mongosh. Below is a full script to execute the attempt.

It seems to be working up until I try to access the value in the returned object.

db.collection1.drop();
db.createCollection("collection1");
db.collection1.insertMany(
    [
        {_id: ObjectId("66477b28bf237b16b21a55b6"), value: "value1"},
        {_id: ObjectId("66477b28bf237b16b21a55b7"), value: "value2"},
        {_id: ObjectId("66477b28bf237b16b21a55b8"), value: "value3"},
        {_id: ObjectId("66477b28bf237b16b21a55b9"), value: "value4"}
    ]
);
db.collection2.drop();
db.createCollection("collection2");
db.collection2.insertMany([
    {name: "name1", values: ["66477b28bf237b16b21a55b6", "66477b28bf237b16b21a55b7"]},
    {name: "name2", values: ["66477b28bf237b16b21a55b6", "66477b28bf237b16b21a55b8"]},
    {name: "name3", values: ["66477b28bf237b16b21a55b7", "66477b28bf237b16b21a55b9"]},
    {name: "name4", values: ["66477b28bf237b16b21a55b8", "66477b28bf237b16b21a55b9"]}
]);

// 
let valueId = db.collection1.aggregate([
    {$match: {value: "value4"}},
    {$project: {idString: {"$toString": "$_id"}}}
]);
print(valueId);
// The print statement above shows:
//{
//  _id: ObjectId('66477b28bf237b16b21a55b9'),
//  idString: '66477b28bf237b16b21a55b9'
//}

// This works:
//db.collection2.updateMany({}, {
//        $pull: { values: "66477b28bf237b16b21a55b9" }
//    }
//);

// This does not:
db.collection2.updateMany({}, {
        $pull: { values: valueId.idString }
    }
);

The variable valueId is the result of aggregate() which is a cursor.

If you are absolutely sure you get a single document from your aggregation you may use

    valueId.toArray[0].idString

to get the value you want.

However, I think it is best to iterate the cursor. See

Dear @Michael_Salvatore, it has been a week since I provided input to your post.

I would appreciate some followup. If my post solve you issue please mark it as the solution. This provides confidence to other readers that may face the same problem.

I’m out of town and unable to check it for the next week or so.

I’ll respond properly when I can test it.

1 Like