0

I wanted to do a query to match documents in one collection with documents in another collection based upon a value which should be contained in both sets of documents but, as I have been informed that Mongo does not support a JOIN, I believe I can't do what I want in the way I want to.

My alternative method then is to insert a document into the collection (col1) where I want to do a query and update which contains an array of all the unique cycle number which are in the other collection (col2).

Collection 1 (Col 1)

        {
        "_id" : ObjectId("5670961f910e1f54662c11ag"),
        "objectType" : "Account Balance",
        "Customer" : "Thomas Brown",
        "status" : "unprocessed",
        "cycle" : "1234"
    }, 
    {
        "_id" : ObjectId("5670961f910e1f54662c12fd"),
        "objectType" : "Account Balance",
        "Customer" : "Luke Underwood",
        "status" : "unprocessed",
        "cycle" : "1235"
    }

Collection 2 (Col 2)

        {
        "_id" : ObjectId("5670961f910e1f54662c1d9d"),
        "objectOrigin" : "Xero",
        "Value" : "500.00",
        "key" : "grossprofit",
        "cycle" : "1234",
        "company" : "e56e09ef-5c7c-423e-b699-21469bd2ea00"
    }, 
    {
        "_id" : ObjectId("5670961f910e1f54662c1d9f"),
        "objectOrigin" : "Xero",
        "Value" : "500.00",
        "key" : "grossprofit",
        "cycle" : "1234",
        "company" : "0a514db8-1428-4da6-9225-0286dc2662c1"
    }, 
    {
        "_id" : ObjectId("5670961f910e1f54662c1da0"),
        "objectOrigin" : "Xero",
        "Value" : "-127.28",
        "key" : "grossprofit",
        "cycle" : "1234",
        "company" : "c2d0561c-dc5d-44b9-beaf-d69a3472a2b8"
    }, 
    {
        "_id" : ObjectId("5670961f910e1f54662c1da1"),
        "objectOrigin" : "Xero",
        "Value" : "-127.28",
        "key" : "grossprofit",
        "cycle" : "1235",
        "company" : "c3fbe6e4-962a-45f6-9ce3-71e2a588438c"
    }

So I want to create a document in collection 1 which looks like this:

    {
        "_id" : ObjectId("5670961f910e1f54662c1d9f"),
        "objectType" : "Status Updater",
        "cycles" : ["1234","1235"]
    }

Now what I want to do is query ALL documents where cycle = cycles and update "status" to "processed". I believe I would do this with a findAndModify with multi : true but not entirely sure.

When finished, I will just simply delete any document in the Collection 1 where objectType is "Status Updater".

4

1 回答 1

0

如果我理解正确,你想

  • a) 更新集合#1 中的所有文档,其中 的值cycle 存在于集合#2 中。
  • b) 此外,您的类型文档"objectType" : "Status Updater"只是一个临时文档,用于跟踪所有循环值。

我认为您可以跳过 b) 并使用以下代码(此代码需要在 mongo shell 中执行):

# get values of all unique cycle values
# returns an array containing: ["1234", "1235", ...]
values = db.coll2.distinct("cycles", {})

# find all documents where cycles value is in the values array 
# and update their status.
db.coll1.update({cycles: {$in: values}}, {$set: {status: "processed"}}, {multi: true})
于 2015-12-16T03:03:53.753 回答