开发者

Mongo: Selecting X elements from an array placed in an object

开发者 https://www.devze.com 2023-04-09 18:59 出处:网络
I have the following collection for a user in a MongoDB: { \"_id\" : 1, \"facebook_id\" : XX, \"name\": \"John Doe\",

I have the following collection for a user in a MongoDB:

{
  "_id" : 1,
  "facebook_id" : XX,
  "name": "John Doe",
  "points_snapshot" : [{
      "unix_timestamp" : 1312300552,
      "points" : 115
    }, {
      "unix_timestamp" : 1312330380,
      "points" : 110
    }, {
      "unix_timestamp" : 1312331610,
      "points" : 115
    }]
}

Is it possible to write one query which by which I can get the user for id 1 along with the snapshots after a particular day. eg: 1312330300?

Basically limit the snapshots to X numbers matching some criteria?

So far, I have tried in C#:

Query.And(
 Query.EQ("facebook_id", XX), 
 Query.GTE("points_snapshot.unix_timestamp", sinceDateTimeStamp)))
 .SetFields("daily_points_snapshot", "facebook_id")

which I soon realised will not work for what I want.

Any help will be appreciated! Thanks!

EDIT: My 开发者_JS百科Solution to this

If anyone is looking to get a quick fix to this, this is what I ended up doing:

var points = MyDatabase[COLLECTION_NAME]
                .Find(Query.EQ("facebook_id", XX))
                .SetFields("points_snapshot", "facebook_id")
                .FirstOrDefault();

if (points != null) {
        var pointsArray = points.AsBsonDocument["points_snapshot"].AsBsonArray
        .Where(x => x.AsBsonDocument["unix_timestamp"].AsInt32 > sinceDateTimeStamp)
        .ToList();

        return pointsArray;
}


Is it possible to write one query which by which I can get the user for id 1 along with the snapshots after a particular day. eg: 1312330300?

Not possible.

The problem here is that MongoDB queries return all matching Documents. Your Document contains an array of objects, but MongoDB does not treat these as "Documents".

Now, you can limit the fields that are returned, but in your case you actually want to limit the "portions of an array" that are returned.

This is a long-outstanding issue, the JIRA ticket is here. The ticket is dated about 18 months ago and it continues to get pushed back. So if this type of query is critical to your architecture, you may have to re-design the architecture.

0

精彩评论

暂无评论...
验证码 换一张
取 消