user1070663
user1070663

Reputation: 23

Querying across a collection in MongoDB

I have a document that was stored through the C# driver. It has a property of SortedList. Here's how the document looks in MongoDB:

{
  "_id": {
    "$oid": "47f1f704c42f56380ac80000"
  },
  "Things": {
    "abc": {
      "Color": "blue",
      "Shape": "square",
    }
    "def": {
      "Color": "red",
      "Shape": "circle"
    }
   }
}

Here Things is the SortedList, and MyClass has properties of Color and Shape. The problem I'm having is trying to query inside Things.

Specifically, what I want to do is set the color of every MyClass that has a certain color. I can't figure out how to do it since it's indexed on what seems to be effectively a dynamic field name.

Upvotes: 1

Views: 340

Answers (2)

Tyler Brock
Tyler Brock

Reputation: 30136

The best thing to do might be changing your document structure.

Make the "things" key point to an array of MyClass and take what you were using as they key and make it the name key of the documents in the array.

{
  "_id": {
    "oid": "47f1f704c42f56380ac80000"
  },
  "Things": [
    {
      "Name": "abc",
      "Color": "blue",
      "Shape": "square",
    },
    {
      "Name": "def",
      "Color": "red",
      "Shape": "circle"
    }
  ]
}

Once you have the document setup that way you can use the positional operator to update the first MyClass in the Things array that matches your query like this:

db.things.update( { "Things.Color": "blue" }, {$set: {"Things.$.Color": "red"} })

If you want to change all of the matching items, what you actually asked about, you probably need to do a $where query that iterates over the Things in the array.

Upvotes: 1

Joe
Joe

Reputation: 386

What's 'abc' and 'def'? Never tried serializing a SortedList. If you use a List of T it will create an embedded array instead of the embedded document you have here.

You can query inside embedded documents and arrays using the dot notation, but here you'd have to do Things.abc.Color or Things.def.Color.

Upvotes: 0

Related Questions