You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MongoDB的Slice查询转换为Golang代码?现有写法无结果

Fixing Your MongoDB $slice Projection in Go

Let's figure out why your Go code isn't returning results and fix it up. First, let's recap what your original MongoDB shell query does:

db.con.find({"repoid":1356485},{"contr":{$slice:[0,10]}}).pretty()

This query finds documents where repoid equals 1356485, and only returns the first 10 elements of the contr array field (instead of the entire array).

What's Wrong With Your Current Code?

Your attempt has two key issues:

  1. Mismatched query field: You used "id": ID instead of "repoid": 1356485 (or your corresponding variable). If your documents use repoid as the field name, this will never match any documents.
  2. Incorrect $slice syntax: You wrapped the field name inside the $slice array ([]interface{}{"$contr", offset, limit}), which isn't how MongoDB's projection works. The $slice operator only expects the skip and limit values in its array—you already specify the target field (contr) as the key in the projection document.

Correct Go Implementations

Using the Official MongoDB Go Driver

If you're using the modern official driver (go.mongodb.org/mongo-driver), here's how to structure the query properly:

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	// Connect to MongoDB (adjust your URI as needed)
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		panic(err)
	}
	defer client.Disconnect(context.TODO())

	// Define your query filter and projection
	targetRepoID := 1356485
	filter := bson.M{"repoid": targetRepoID}
	// $slice takes [skip, limit] directly—no need to include the field name here
	projection := bson.M{"contr": bson.M{"$slice": []int{0, 10}}}

	// Get the collection
	coll := client.Database("your_database_name").Collection("con")

	// Execute the query with projection
	cursor, err := coll.Find(context.TODO(), filter, options.Find().SetProjection(projection))
	if err != nil {
		panic(err)
	}
	defer cursor.Close(context.TODO())

	// Decode results into a slice
	var results []bson.M
	if err = cursor.All(context.TODO(), &results); err != nil {
		panic(err)
	}

	// Print formatted results (similar to .pretty())
	for _, result := range results {
		jsonData, _ := bson.MarshalExtJSON(result, false, false)
		fmt.Println(string(jsonData))
	}
}

Using the Legacy mgo Driver

If you're still using the older mgo driver (gopkg.in/mgo.v2), the syntax is slightly simpler with the .Select() method:

package main

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func main() {
	// Connect to MongoDB
	session, err := mgo.Dial("mongodb://localhost:27017")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Get the collection
	c := session.DB("your_database_name").C("con")

	// Define filter and projection
	targetRepoID := 1356485
	filter := bson.M{"repoid": targetRepoID}
	projection := bson.M{"contr": bson.M{"$slice": []int{0, 10}}}

	// Execute query and decode results
	var results []bson.M
	err = c.Find(filter).Select(projection).All(&results)
	if err != nil {
		panic(err)
	}

	// Print results
	for _, res := range results {
		fmt.Printf("%+v\n", res)
	}
}

Troubleshooting Tips If You Still Have Issues

  • Verify data exists: Run your original shell query again to confirm there are documents matching repoid:1356485 with non-empty contr arrays.
  • Check field names: Double-check that your Go code uses the exact same field names as your MongoDB documents (case matters—repoid vs RepoID will not match).
  • Log the actual query: Enable MongoDB's query logging to see what exact query your Go code is sending. Compare it to your working shell query to spot discrepancies.
  • Test without projection first: Try querying without the $slice projection to see if you get any results. If you do, the issue is definitely with the projection syntax.

内容的提问来源于stack exchange,提问作者Chirag Painter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:03:15